这可能很简单,我只是一个大脑放屁。我有几年的专栏。我如何进行查询以逐年分解?例如:
Code - Date - CustName - Sales
1001 - 2011-01-12 - Sparkies - 50
1002 - 2012-02-11 - Spankies - 125
1001 - 2013-01-12 - Sparkies - 60
1003 - 2011-05-05 - Squirrelies - 75
我想要一份报告显示:
Code - CustName - 2011 - 2012 - 2013
1001 - Sparkies - 50 - 0 - 60
1002 - Spankies - 0 - 125 - 0
1003 - Squirrelies - 75 - 0 - 0
这是在MSSQL 2008 R2中。提前谢谢......
答案 0 :(得分:3)
您可以使用PIVOT功能获得结果。如果您的值有限,那么您将对查询进行硬编码,类似于:
select code, custname,
[2011], [2012], [2013]
from
(
select code, year(date) dt,
custname, sales
from yourtable
) d
pivot
(
sum(sales)
for dt in ([2011], [2012], [2013])
) piv;
但是如果你的年数不详,那么你需要考虑使用动态SQL来获得最终结果:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(year(date))
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT code, custname, ' + @cols + '
from
(
select code, year(date) dt,
custname, sales
from yourtable
) x
pivot
(
sum(sales)
for dt in (' + @cols + ')
) p '
execute sp_executesql @query;
见SQL Fiddle with Demo。这些将产生以下结果:
| CODE | CUSTNAME | 2011 | 2012 | 2013 |
|------|-------------|--------|--------|--------|
| 1001 | Sparkies | 50 | (null) | 60 |
| 1002 | Spankies | (null) | 125 | (null) |
| 1003 | Squirrelies | 75 | (null) | (null) |
答案 1 :(得分:1)
您可以使用以下内容:
SELECT
[Code],
[CustName],
SUM(CASE WHEN YEAR([Date]) = 2011 THEN [Sales] ELSE 0 END) AS [2011],
SUM(CASE WHEN YEAR([Date]) = 2012 THEN [Sales] ELSE 0 END) AS [2012],
SUM(CASE WHEN YEAR([Date]) = 2013 THEN [Sales] ELSE 0 END) AS [2013]
FROM
[Table]
GROUP BY
[Code],
[CustName]
或者,如果您愿意,请查看使用PIVOT
。
答案 2 :(得分:-1)
SELECT CAST(YEAR(Date) AS VARCHAR(4)) AS Year, SUM(Sales) AS Sales
FROM Orders
GROUP BY CAST(YEAR(Date) AS VARCHAR(4))
ORDER BY Year