CREATE TABLE TestRowCol (
name VARCHAR(10),
place VARCHAR(10),
valuw INT
);
INSERT INTO TestRowCol VALUES ('张三', '东', 1);
INSERT INTO TestRowCol VALUES ('张三', '南', 2);
INSERT INTO TestRowCol VALUES ('张三', '西', 3);
INSERT INTO TestRowCol VALUES ('张三', '北', 4);
INSERT INTO TestRowCol VALUES ('李四', '东', 5);
INSERT INTO TestRowCol VALUES ('李四', '南', 6);
INSERT INTO TestRowCol VALUES ('李四', '西', 7);
INSERT INTO TestRowCol VALUES ('李四', '北', 8);
将标题为
name place valuw
---------- ---------- -----------
修改为
Name 东 南 西 北
CASE WHEN + GROUP BY处理
SELECT
name,
SUM(CASE WHEN place = '东' THEN valuw ELSE '0' END) AS 东,
SUM(CASE WHEN place = '南' THEN valuw ELSE '0' END) AS 南,
SUM(CASE WHEN place = '西' THEN valuw ELSE '0' END) AS 西,
SUM(CASE WHEN place = '北' THEN valuw ELSE '0' END) AS 北
FROM
TestRowCol
GROUP BY
name
name 东 南 西 北
---------- ----------- ----------- ----------- -----------
李四 5 6 7 8
张三 1 2 3 4
同行列装换--使用CASE WHEN
SELECT
name,
tmp.[东] 东,
tmp.[南] 南,
tmp.[西] 西,
tmp.[北] 北
FROM
TestRowCol
PIVOT(
SUM(valuw)
FOR place IN ([东], [南], [西], [北] )
) tmp
ORDER BY
name