我的Sql表类似于下面的
Code Value ID
A 100 1
A 200 2
A 300 3
B 200 1
B 500 2
B 600 3
C 800 1
C 700 2
C 200 3
如何在sql server 2008中编写查询以获取以下格式的值。
ID A B C
1 100 200 800
2 200 500 700
3 300 600 200
答案 0 :(得分:3)
您可以使用SUM
功能:
SELECT ID,
SUM(CASE Code when 'A' then Value else 0 end)as A,
SUM(CASE Code when 'B' then Value else 0 end)as B,
SUM(CASE Code when 'C' then Value else 0 end)as C
FROM myTable
GROUP BY ID;
答案 1 :(得分:2)
使用PIVOT
select ID,[A],[B],[C]
from your_table T
PIVOT (MAX(Value) FOR Code in ([A],[B],[C]) )P
如果代码未修复,则可以使用动态支点
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Code)
from your_table
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ID, ' + @cols + '
from your_table
pivot
(
MAX([Value])
for Code in (' + @cols + ')
) p '
print(@query)
execute(@query)
答案 2 :(得分:1)
答案是PIVOT
DECLARE @t TABLE (Code varchar(10), Value int, Id int)
INSERT INTO @t VALUES
('A',100,1),
('A',200,2),
('A',300,3),
('B',200,1),
('B',500,2),
('B',600,3),
('C',800,1),
('C',700,2),
('C',200,3);
SELECT ID,[A],[B],[C]
FROM @t
PIVOT (SUM(Value) FOR Code IN ([A],[B],[C]))P
<强>结果强>
ID A B C
1 100 200 800
2 200 500 700
3 300 600 200