Mysql
 SQL >> Database >  >> RDS >> Mysql

Contare quante volte un campo MySQL referenzia un altro

Questo restituisce il conteggio di ID distinti per ref:

select ref, count(distinct id) from table group by ref;

Questo restituisce il numero totale di record per ref:

select ref, count(*) from table group by ref;

Per ottenere l'output descritto, prova:

select t.*, m.counter from table t join ( select ref, count(distinct id) as counter from table group by ref ) m on t.ref = m.ref

Esempio su SQLFiddle: https://sqlfiddle.com/#!9/2b93c/2