Revenue Without Double Counting
The customer revenue report started overstating totals when an order has multiple line items. Count only payments with status = 'success', without multiplying them by product lines. Return id, name, and revenue; users with no successful payments get 0, sorted by id.
Buggy query
SELECT u.id, u.name, COALESCE(SUM(p.amount), 0) AS revenue FROM users u LEFT JOIN orders o ON o.user_id = u.id LEFT JOIN order_items oi ON oi.order_id = o.id LEFT JOIN payments p ON p.order_id = o.id AND p.status = 'success' GROUP BY u.id, u.name ORDER BY u.id;
Ukázka očekávaného výstupu
Takto vypadá správná odpověď — počet řádků je její vlastní, nemusí odpovídat tabulkám schématu.
| id | name | revenue |
|---|---|---|
| 1 | Alice | 73 |
| 2 | Bob | 0 |
| 3 | Carol | 6 |
Přihlaste se, abyste viděli historii odevzdání
Přihlásit sePřihlaste se, abyste mohli použít AI mentora
Přihlásit se