我使用CASE WHEN语句返回不同的产品'我的数据集中某些时期的名称和价格,但每个唯一产品返回的行数很多。这是不正确使用CASE WHEN,如果是这样,我将如何解决这个问题?
SELECT product_name,
CASE WHEN period_fiscal_year=1 THEN product_price ELSE 0 END as Period_1,
CASE WHEN period_fiscal_year=2 THEN product_price ELSE 0 END as Period_2,
CASE WHEN period_fiscal_year=3 THEN product_price ELSE 0 END as Period_3
FROM product_table
理想情况下,结果应如下所示(一个示例):
|product_name|Period_1|Period_2|Period_3|
|1st Product | $25 | $35 | $20 |
目前,它看起来像:
|product_name|Period_1|Period_2|Period_3|
|1st Product | $25 | 0 | 0 |
|1st Product | 0 | $35 | 0 |
|1st Product | 0 | 0 | $20 |
|1st Product | 0 | 0 | 0 |
如何整合这些行,从而删除0值?谢谢!
答案 0 :(得分:2)
您似乎在表格中有第一个产品的多个条目,这就是为什么您需要汇总product_name
级别的不同期间的价格。
SELECT product_name,
SUM(CASE WHEN period_fiscal_year=1 THEN product_price ELSE 0 END) as Period_1,
SUM(CASE WHEN period_fiscal_year=2 THEN product_price ELSE 0 END) as Period_2,
SUM(CASE WHEN period_fiscal_year=3 THEN product_price ELSE 0 END) as Period_3
FROM product_table
GROUP BY product_name;