我有SQL查询返回像这样的行数据......
name1 aa 12
name1 bb 32
name2 aa 21
name3 aa 11
name3 bb 23
name3 cc 22
并且想要像这样格式化它......
aa bb cc
name1 12 32 0
name2 21 0 0
name3 11 23 22
列结果是动态的,我不能在它们上使用连接。
答案 0 :(得分:2)
以下PIVOT
查询按预期工作。
DECLARE @table TABLE(name VARCHAR(40), id VARCHAR(10), total INT)
INSERT INTO @table
SELECT 'name1','aa', 12 UNION
SELECT 'name1','bb', 32 UNION
SELECT 'name2','aa', 21 UNION
SELECT 'name3','aa', 11 UNION
SELECT 'name3','bb', 23 UNION
SELECT 'name3','cc', 22
SELECT name,
ISNULL([aa], 0) AS [aa],
ISNULL([bb], 0) AS [bb],
ISNULL([cc], 0) AS [cc]
FROM @table
PIVOT(
SUM(total)
FOR id IN ([aa], [bb], [cc])
) AS pivTab
答案 1 :(得分:1)
您应该使用PIVOT
。
CREATE TABLE #Temp2 (
Col1 VARCHAR(10),
Col2 NVARCHAR(40),
Col3 INT
);
INSERT INTO #Temp2 (Col1, Col2, Col3)
VALUES ('name1', 'aa', 12),
('name1', 'bb', 32),
('name2', 'aa', 21),
('name3', 'aa', 11),
('name3', 'bb', 23),
('name3', 'cc', 22);
SELECT Col1,
ISNULL([aa], 0) as aa,
ISNULL([bb], 0) as bb,
ISNULL([cc], 0) as cc
FROM #Temp2
PIVOT
(
MIN(col3)
FOR col2 IN ([aa], [bb], [cc])
) as pvt
DROP TABLE #Temp2
<强>输出强>
Col1 aa bb cc
name1 12 32 0
name2 21 0 0
name3 11 23 22