我在tbl1中有数据:
item date amount
a 1 10
a 2 20
a 3 30
a 4 40
b 1 20
b 2 30
b 3 40
b 4 50
c 1 30
c 2 40
c 3 50
c 4 60
但我需要如下
item 1 2 3 4
a 10 20 30 40
b 20 30 40 50
c 30 40 50 60
答案 0 :(得分:2)
使用PIVOT
SELECT item, [1], [2], [3], [4]
FROM tbl1 t
PIVOT (SUM(amount) FOR date IN ([1], [2], [3], [4])) p
SELECT item, [10], [20], [30], [40], [50], [60]
FROM tbl1 t
PIVOT (MAX(date) FOR amount IN ([10], [20], [30], [40], [50], [60])) p
输出:
item 1 2 3 4
a 10 20 30 40
b 20 30 40 50
c 30 40 50 60
答案 1 :(得分:0)
您可以使用GROUP BY
这样的条件聚合CASE
。
示例数据
DECLARE @tbl1 TABLE (item CHAR(1),date int, amount int)
INSERT INTO @tbl1 VALUES
('a', 1, 10),
('a', 2, 20),
('a', 3, 30),
('a', 4, 40),
('b', 1, 20),
('b', 2, 30),
('b', 3, 40),
('b', 4, 50),
('c', 1, 30),
('c', 2, 40),
('c', 3, 50),
('c', 4, 60);
<强>查询强>
SELECT
item,
MAX(CASE WHEN date = 1 then amount END) as d1,
MAX(CASE WHEN date = 2 then amount END) as d2,
MAX(CASE WHEN date = 3 then amount END) as d3,
MAX(CASE WHEN date = 4 then amount END) as d4
FROM @tbl1
GROUP BY item
<强>输出强>
item d1 d2 d3 d4
a 10 20 30 40
b 20 30 40 50
c 30 40 50 60
修改强>
如果您的日期数量未知,请使用此类dynamic pivot
。
DECLARE @s NVARCHAR(MAX)
SELECT @s = STUFF((SELECT DISTINCT ',' + quotename(CONVERT(VARCHAR(10),date),'[')
FROM #tbl1 for xml path('')),1,1,'')
SET @s = N'SELECT item,' + @s + ' FROM #tbl1 PIVOT(MAX(amount) FOR date in(' + @s + ')) as pvt'
print @s
EXEC sp_executeSQL @s
答案 2 :(得分:0)
USE PIVOT
使用pivot概念将行值转换为列标题
PIVOT
是Sql Server 2005中引入的新关系运算符之一。它在Sql Server中提供了一种将行转换为列的简单机制。
select * from tbl1 pivot(sum(amount) for [date] in([1],[2],[3],[4])) as a