您可以使用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 Fiddle with Demo
但如果你有一個未知的數年,那麼你就需要看看使用動態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) |
您使用MYSQL/MS SQL嗎? – Deepshikha
編輯添加:MSSQL 2008 R2 – user3059028
對於給定的'CustName',每年是否會有多於一行?如果是這樣,該行/列的最終價值是什麼?和?民?馬克斯?平均? –