我正在尝试比较同比数据,并且正在尝试使用案例语句以便按年份分割。我一直在尝试做的是
(Case
When year(date) = 2010 Then 'sales year 2010'
When year(date) = 2011 Then 'sales year 2011'
Else
End) as Year
Run Code Online (Sandbox Code Playgroud)
但上面的方法不起作用,因为我想按列获取每年的数据,而不是同一列下的行。
所以,接下来我尝试的是
(Case
When year(date) = 2010 Then sum(sales) End) as 'sales year 2010',
(Case
When year(date) = 2011 Then sum(sales) End) as 'sales year 2011'
Run Code Online (Sandbox Code Playgroud)
我得到了以下内容。
| 物品 | 2010年销售年度 | 2011年销售年度 |
|---|---|---|
| A | 无效的 | 2,500 人 |
| A | 5,000 | 无效的 |
| 乙 | 无效的 | 200 |
| 乙 | 7,000 | 无效的 |
| C | 无效的 | 2,500 人 |
| C | 5,000 | 无效的 |
| D | 无效的 | 200 |
| D | 7,000 | 无效的 |
我想要得到的是这个。
| 物品 | 2010年销售年度 | 2011年销售年度 |
|---|---|---|
| A | 5,000 | 2,500 人 |
| 乙 | 7,000 | 200 |
| C | 5,000 | 2,500 人 |
| D | 7,000 | 200 |
有人可以建议如何做吗?
谢谢。
您想要对CASE此处的表达式求和:
SELECT
Item,
SUM(CASE WHEN year = 2010 THEN sales ELSE 0 END) AS [Sales Year 2010],
SUM(CASE WHEN year = 2011 THEN sales ELSE 0 END) AS [Sales Year 2011]
FROM yourTable
GROUP BY Item;
Run Code Online (Sandbox Code Playgroud)