横列相互转换
列转行
1 WITH T 2 AS 3 ( 4 SELECT 1 as TeamId, '测试团队1' as Team, 80 'MEN', 20 'WOMEN', 99 'add' 5 UNION 6 SELECT 2 as TeamId, '测试团队2' as Team, 30 'MEN', 70 'WOMEN', 99 'add' 7 ) 8 ------------列传行---------------- 9 SELECT TeamId,Team,TYPE=ATTRIBUTE,CNT=VALUE 10 FROM T 11 UNPIVOT ( 12 VALUE FOR ATTRIBUTE IN ([MEN],[WOMEN],[add]) 13 ) AS UPV
查询结果如下截图所示:
行转列
1 WITH T 2 AS 3 ( 4 SELECT 1 AS ID,'测试团队1' TEAM,'MEN' ITEM,80 CENT 5 UNION 6 SELECT 1 AS ID,'测试团队1' TEAM,'WOMEN' ITEM,20 CENT 7 UNION 8 SELECT 2 AS ID,'测试团队2' TEAM,'MEN' ITEM,30 CENT 9 UNION 10 SELECT 2 AS ID,'测试团队2' TEAM,'WOMEN' ITEM,70 CENT 11 ) 12 -- 13 --SELECT * FROM T RIVOT (SUM(CENT) FOR ITEM IN ([MEN],[WOMEN])) A 14 --error 15 --消息 321,级别 15,状态 1,第 12 行 16 --SUM 不是可识别的表提示选项。如果它要作为表值函数或 CHANGETABLE 函数的参数,请确保您的数据库兼容模式设置为 90。 17 18 SELECT ID,TEAM, 19 SUM(CASE WHEN ITEM='MEN' THEN CENT ELSE 0 END) 'MEN', 20 SUM(CASE WHEN ITEM='WOMEN' THEN CENT ELSE 0 END) 'WOMEN' 21 FROM T 22 GROUP BY ID, TEAM
查询结果如下截图所示:
参考自:快乐地编程