我写了一个如下所示的查询:
SELECT
id,
product_name,
CASE WHEN by_month = 'January 2018' THEN total_sales ELSE 0 END AS january_2018,
CASE WHEN by_month = 'February 2018' THEN total_sales ELSE 0 END AS february_2018,
CASE WHEN by_month = 'March 2018' THEN total_sales ELSE 0 END AS march_2018,
CASE WHEN by_month = 'April 2018' THEN total_sales ELSE 0 END AS april_2018
FROM (
SELECT
mnth,
id,
product_name,
CASE WHEN mnth = '2018-01-01' THEN 'January 2018'
WHEN mnth = '2018-02-01' THEN 'February 2018'
WHEN mnth = '2018-03-01' THEN 'March 2018'
WHEN mnth = '2018-04-01' THEN 'April 2018' END AS by_month,
SUM(sales) total_sales
FROM (
SELECT
date_trunc('month', event_date) mnth,
id,
product_name,
SUM(sales) sales
FROM
table1
WHERE event_date BETWEEN '2017-01-01' AND '2018-04-30'
1,2,3)
WHERE sales > 0
GROUP BY
1,2,3,4)
GROUP BY
1,2, by_month, total_sales
但这会产生一个非常零散的结果,看起来像这样
id product_name january_2018 february_2018 march_2018 april 2018
123 abc 500 0 0 0
123 abc 0 700 0 0
123 abc 0 0 900 0
123 abc 0 0 0 100
我想要的是消除'0'结果(我知道这是我故意在ELSE
语句中添加但我需要一个占位符。
我希望结果看起来像这样。
id product_name january_2018 february_2018 march_2018 april 2018
123 abc 500 700 900 100
如何实现这一目标?它会出现在ELSE
语句中还是其他子查询中?或其他什么?
答案 0 :(得分:0)
使用聚合:
SELECT id, product_name,
SUM(CASE WHEN by_month = 'January 2018' THEN total_sales ELSE 0 END) AS january_2018,
SUM(CASE WHEN by_month = 'February 2018' THEN total_sales ELSE 0 END) AS february_2018,
SUM(CASE WHEN by_month = 'March 2018' THEN total_sales ELSE 0 END) AS march_2018,
SUM(CASE WHEN by_month = 'April 2018' THEN total_sales ELSE 0 END) AS april_2018
FROM table_name
GROUP BY id, product_name
答案 1 :(得分:0)
对于更清晰的聚合,您可以将FILTER子句与聚合函数一起使用,如下所示:
SELECT
id,
product_name,
SUM(total_sales) FILTER (WHERE by_month = 'January 2018') AS january_2018,
SUM(total_sales) FILTER (WHERE by_month = 'February 2018') AS february_2018,
SUM(total_sales) FILTER (WHERE by_month = 'March 2018') AS march_2018,
SUM(total_sales) FILTER (WHERE by_month = 'April 2018') AS april_2018
FROM
table_name
GROUP BY
id,
product_name
它是SQL:2003标准功能,但目前仅支持PostgreSQL。有关详细信息,请参阅The FILTER clause: Selective Aggregates