Reputation: 15
I have two tables Order
with columns:
orderId(int), name(varchar), customerId(int), sent(bool), deleted(bool)
And Customer
with columns:
customerId(int), name(varchar), address(varchar), deleted(bool)
I need to return all Customer
columns, with additional TotalOrders
count and TotalSentOrders
count columns (for each customer) for the Customers and Orders that deleted = false
and count 0 if there are no orders or sent orders.
Expected Outcome:
|customerId|name|address|deleted|TotalOrders|TotalSentOrders|
| 1 |John| A St. | false | 0 | 0 |
| 2 |Jack| B St. | false | 5 | 1 |
| 3 |Luke| C St. | false | 4 | 0 |
I'm doing this in PostgreSQL 9.6
Upvotes: 1
Views: 884
Reputation: 23756
SELECT
c.*,
COUNT(*) FILTER (WHERE o.orderId IS NOT NULL), -- 3
COUNT(*) FILTER (WHERE o.sent = true) -- 4
FROM customer c
LEFT JOIN orders o ON c.customerId = o.customerId -- 1
WHERE c.deleted = false AND o.deleted = false -- 2
GROUP BY c.customerId, c.name, c.address, c.deleted
LEFT JOIN
both tables, to keep John
s datadeleted
GROUP BY
customer and COUNT
the remaining records. Because John
is still in the result set, he would be counted as well. To ensure you only count the orders you could use the FILTER
clause to adjust the aggregate function.FILTER
clause once more to COUNT
only the sent
orders.Upvotes: 1