MySQL: Null zurückgeben, wenn kein Wert vorhanden ist, monatlich kategorisiert
-
20-09-2019 - |
Frage
Ich habe die folgenden zwei Tabellen, die Ausgaben aufzeichnen und Informationen zur Ausgabenkategorie bereitstellen:
Tabellentransaktionen:
+-------+--------+--------+
| month | cat_id | amount |
+-------+--------+--------+
| 1 | 2 | 3 |
| 1 | 2 | 8 |
| 2 | 1 | 7 |
| 2 | 1 | 5 |
+-------+--------+--------+
Tabellenkategorien:
+--------+-------------+
| cat_id | cat_desc |
+--------+-------------+
| 1 | Stock |
| 2 | Consumables |
+--------+-------------+
Ich möchte eine Abfrage erstellen, in der eine Summe der Beträge für jede Kategorie für jeden Monat angezeigt wird, auch wenn in dieser Kategorie für diesen Monat keine Ausgaben vorhanden sind:
+-------+-------------+--------+
| month | cat_desc | amount |
+-------+-------------+--------+
| 1 | Stock | 0 |
| 1 | Consumables | 11 |
| 2 | Stock | 12 |
| 2 | Consumables | 0 |
+-------+-------------+--------+
Ich vermute, dass ein äußerer Join verwendet werden müsste, aber ich habe noch keine Aussage gefunden, um dies zu tun.
Vielen Dank für jede Hilfe.
Lösung
Dieser sollte Ihnen das richtige Ergebnis liefern. Die innere Auswahl erstellt eine Liste aller Monate in Kombination mit allen Kategorien und der LEFT JOIN
Griff den Rest.
SELECT t.month, t.cat_desc, COALESCE(SUM(t2.amount), 0) amount
FROM (
SELECT DISTINCT t.month, c.cat_id, c.cat_desc
FROM categories c
CROSS JOIN transactions t
) t
LEFT JOIN transactions t2 ON ( t2.month = t.month AND t2.cat_id = t.cat_id )
GROUP BY t.month, t.cat_desc
Leistung kann mit Folgendem besser sein (mit Verwendung DISTINCT
nur gegebenenfalls), aber Sie müssen es versuchen:
SELECT t.month, t.cat_desc, COALESCE(SUM(t2.amount), 0) amount FROM (
SELECT t.month, c.cat_id, c.cat_desc
FROM
(SELECT DISTINCT month FROM transactions) t
CROSS JOIN categories c
) t
LEFT JOIN transactions t2 ON ( t2.month = t.month AND t2.cat_id = t.cat_id )
GROUP BY t.month, t.cat_desc
Andere Tipps
SELECT c.cat_id, c.cat_desc,t.month, SUM(t.amount)
FROM categories c
LEFT JOIN transactions t ON (t.cat_id = c.cat_id)
GROUP BY c.cat_id,t.month
SELECT c.cat_id, c.cat_desc,t.month, SUM(t.amount)
FROM categories c
LEFT JOIN transactions t ON (t.cat_id = c.cat_id)
GROUP BY t.month,c.cat_id
Order By t.month