假设我在产品日期有一张销售表。唉,我不能在这里格式化表格,因此代码为:
table1:
Product|Date|Sales
-------|----|-----
ProdA |1.1.|100
ProdB |1.1.| 50
ProdC |1.1.| 75
ProdA |2.1.|110
ProdB |2.1.| 60
ProdC |2.1.| 60
.... |... |...
我需要一个包含每月销售额的新表:
Product| Jan| Feb|...
-------|----|----|...
ProdA |1234|1400|...
ProdB | 234| 400|...
ProdC | 524| 640|...
... |... |... |...
我尝试使用CASE
的SQL查询。 []中的文字是缩写,真正的表达式是to_char(to_month(..)) construct
,可以使用。
SELECT
Product,
CASE WHEN [date == 1] THEN SUM(Sales) END AS Jan,
CASE WHEN [date == 2] THEN SUM(Sales) END AS Feb,
CASE WHEN [date == 3] THEN SUM(Sales) END AS Mar,
...
FROM
table1
GROUP BY
Product
我收到00979. 00000 - "not a GROUP BY expression"
错误。
我知道我可以通过每月构建表格并再次添加一些表来解决,但这是低性能的。我也想了解,为什么构造不起作用?
PS: - [Edit1]:它是一个Oracle DB
答案 0 :(得分:4)
尝试在agreegation
声明case
sum(case when end)
SELECT
Product,
sum(CASE WHEN date = 1 THEN Sales END) AS Jan,
SUM(CASE WHEN date = 2 THEN Sales END) AS Feb,
SUM(CASE WHEN date = 3 THEN Sales END) AS Mar,
...
FROM
table1
GROUP BY
Product