我正在try 创建一份每年销售额的汇总报告,其中包含几个表,如下所示:
products |
---|
id (PK) |
[... ] |
Orders |
---|
id (PK) |
date |
product_id (FK to products |
我已经编写了一个查询,其中我从从最早的订单到最近的订单构建的时间序列中进行 Select ,然后将其与两个表连接在一起,按product_id和Year时间戳分组:
SELECT
date_trunc('year'::text, years) AS year,
products.id as product_id,
coalesce(count(o.id),0) AS total_orders
FROM generate_series(
(select MIN(orders.date) from orders),
(select MAX(orders.date) from orders),
'1 year'::interval
) years
left JOIN orders o ON date_trunc('year'::text, years) = date_trunc('year'::text, o.date)
join products on products.id = o.product_id
GROUP BY year, products.id
ORDER BY year, products.id
查询的结果如下所示:
year | product_id | total_orders |
---|---|---|
2012-01-01 | 1 | 4 |
2013-01-01 | 1 | 3 |
2013-01-01 | 2 | 1 |
由于左连接,我希望看到另一行合并空结果为零:
year | product_id | total_orders |
---|---|---|
2012-01-01 | 2 | 0 |
当orders
中不存在给定年份的行时,为什么时间序列上的LEFT JOIN没有作为指向零total_orders
的行返回,您知道吗?