SELECT t1.* FROM (SELECT tag, category, COUNT(*) AS count FROM tags INNER JOIN stuff USING (id) GROUP BY tag, category) t1 LEFT OUTER JOIN (SELECT tag, category, COUNT(*) AS count FROM tags INNER JOIN stuff USING (id) GROUP BY tag, category) t2 ON (t1.tag = t2.tag AND (t1.count < t2.count OR t1.count = t2.count AND t1.category < t2.category)) WHERE t2.tag IS NULL ORDER BY t1.count DESC;Zugegeben, das ist recht viel für eine einzelne SQL-Abfrage. Jede Verwendung von GROUP BY in einer Unterabfrage lässt mich zusammenzucken. Übersichtlicher wird es mit Views:
CREATE VIEW count_per_category AS SELECT tag, category, COUNT(*) AS count FROM tags INNER JOIN stuff USING (id) GROUP BY tag, category;
SELECT t1.* FROM count_per_category t1 LEFT OUTER JOIN count_per_category t2 ON (t1.tag = t2.tag AND (t1.count < t2.count OR t1.count = t2.count AND t1.category < t2.category)) WHERE t2.tag IS NULL ORDER BY t1.count DESC;Im Hintergrund verrichtet das aber dieselbe Arbeit.
Du sagst, du könntest Ähnliches leicht in Applikationscode erledigen. Warum machst du das dann nicht? Führe die einfachere Abfrage aus, um die Zählwerte pro Kategorie zu erhalten:
SELECT tag, category, COUNT(*) AS count FROM tags INNER JOIN stuff USING (id) GROUP BY tag, category;Und sortiere das Ergebnis anschließend im Applikationscode.