Mysql
 sql >> Database >  >> RDS >> Mysql

SQL:confronto di due conteggi di tabelle diverse

Inizia ottenendo le somme per ciascuno individualmente:

# Sum of lakes
SELECT code, count(*) AS sum FROM lakes GROUP BY code

# Sum of mountains
SELECT code, count(*) AS sum FROM mountains GROUP BY code

Quindi unisci i risultati e seleziona tutte le righe in cui la somma delle montagne per un paese è inferiore al numero di laghi:

SELECT l.code AS code, l.sum AS lake_count, m.sum AS mountain_count
FROM
(SELECT code, count(*) AS sum FROM lakes GROUP BY code) AS l JOIN
(SELECT code, count(*) AS sum FROM mountains GROUP BY code) AS m
ON l.code = m.code
WHERE m.sum < l.sum