Ich habe eine Tabelle wie folgt aus:Was ist SQL, um eine Eigenschaft und die maximale Anzahl der Vorkommen einer verwandten Eigenschaft auszuwählen?
Table: p
+----------------+
| id | w_id |
+---------+------+
| 5 | 8 |
| 5 | 10 |
| 5 | 8 |
| 5 | 10 |
| 5 | 8 |
| 6 | 5 |
| 6 | 8 |
| 6 | 10 |
| 6 | 10 |
| 7 | 8 |
| 7 | 10 |
+----------------+
Was ist die beste SQL das folgende Ergebnis zu bekommen? :
+-----------------------------+
| id | most_used_w_id |
+---------+-------------------+
| 5 | 8 |
| 6 | 10 |
| 7 | 8 |
+-----------------------------+
Mit anderen Worten, zu bekommen, pro id
, die am häufigsten verwandten w_id
. Beachten Sie, dass sich id
7 im obigen Beispiel auf 8 einmal und auf 10 einmal bezieht. Also, entweder (7, 8) oder (7, 10) wird als Ergebnis tun. Wenn es nicht möglich ist, eins aufzunehmen, dann sind sowohl (7, 8) als auch (7, 10) im Ergebnissatz in Ordnung.
Ich habe mit so etwas wie kommen:
select counters2.p_id as id, counters2.w_id as most_used_w_id
from (
select p.id as p_id,
w_id,
count(w_id) as count_of_w_ids
from p
group by id, w_id
) as counters2
join (
select p_id, max(count_of_w_ids) as max_counter_for_w_ids
from (
select p.id as p_id,
w_id,
count(w_id) as count_of_w_ids
from p
group by id, w_id
) as counters
group by p_id
) as p_max
on p_max.p_id = counters2.p_id
and p_max.max_counter_for_w_ids = counters2.count_of_w_ids
;
aber ich bin nicht sicher, ob überhaupt, ob dies der beste Weg, es zu tun ist. Und ich musste die gleiche Unterabfrage zweimal wiederholen.
Eine bessere Lösung?
Ihre Tabelle hat keinen Primärschlüssel. Das ist ein Problem. Allerdings ist dies eine gute Lösung. Es ist genau so geschrieben, wie ich es schreiben würde! :-) – Strawberry