SQL: Reporting – code examples
Revenue per Customer
SELECT k.name,
COUNT(DISTINCT b.id) AS bestellungen,
SUM(bp.menge * p.preis) AS umsatz
FROM kunden k
JOIN bestellungen b ON b.kunde_id = k.id AND b.status <> 'storniert'
JOIN bestellpositionen bp ON bp.bestellung_id = b.id
JOIN produkte p ON p.id = bp.produkt_id
GROUP BY k.id, k.name
ORDER BY umsatz DESC;Three joins link customer, order, line item, and product; SUM(menge * preis) computes the revenue. The JOIN condition excludes cancelled orders. COUNT(DISTINCT b.id) is necessary because a join produces several line items per order.
Pivot with CASE
SELECT SUBSTR(datum, 1, 7) AS monat,
SUM(CASE WHEN status = 'bezahlt' THEN 1 ELSE 0 END) AS bezahlt,
SUM(CASE WHEN status = 'offen' THEN 1 ELSE 0 END) AS offen,
SUM(CASE WHEN status = 'storniert' THEN 1 ELSE 0 END) AS storniert
FROM bestellungen
GROUP BY SUBSTR(datum, 1, 7)
ORDER BY monat;A CASE inside an aggregate function counts conditionally. This creates a cross-tab without a dialect-specific PIVOT. PostgreSQL additionally offers COUNT(*) FILTER (WHERE status = 'offen').
Combining Values into One Text
-- SQLite / MySQL: GROUP_CONCAT
SELECT bp.bestellung_id, GROUP_CONCAT(p.name, ', ') AS produkte
FROM bestellpositionen bp JOIN produkte p ON p.id = bp.produkt_id
GROUP BY bp.bestellung_id;
-- PostgreSQL: STRING_AGG(p.name, ', ' ORDER BY p.name)
-- MySQL: GROUP_CONCAT(p.name ORDER BY p.name SEPARATOR ', ')The aggregate name differs by dialect: GROUP_CONCAT (SQLite, MySQL), STRING_AGG (PostgreSQL, SQL Server). Note: MySQL truncates results at group_concat_max_len (default 1024 characters).
Grouping by Month
-- Portable for ISO date texts:
SELECT SUBSTR(registriert, 1, 7) AS monat, COUNT(*) AS neue_kunden
FROM kunden
GROUP BY SUBSTR(registriert, 1, 7)
ORDER BY monat;
-- PostgreSQL: DATE_TRUNC('month', registriert)
-- MySQL: DATE_FORMAT(registriert, '%Y-%m')
-- SQLite: STRFTIME('%Y-%m', registriert)For time series you have to truncate the date to the period and then group. Each dialect has its own function for this; with ISO text dates, SUBSTR works.