日期:2014-05-18 浏览次数:20536 次
--> 测试数据:[test] if object_id('[test]') is not null drop table [test] create table [test]([name] varchar(4),[sub] varchar(4),[score] int) insert [test] select '张三','.net',80 union all select '张三','java',85 union all select '张三','SQL',95 union all select '李四','.net',86 union all select '李四','java',92 union all select '王五','.net',96 union all select '王五','java',88 union all select '王五','SQL',78 select * from [test] pivot (max([Score]) for [sub] in([.net],[java],[SQL]))b /* name .net java SQL 李四 86 92 NULL 王五 96 88 78 张三 80 85 95 */
------解决方案--------------------
create table tbc (name VARCHAR(100), sub VARCHAR(100), score INT) insert into tbc SELECT '张三', '.net', 80 UNION SELECT '张三', 'java', 85 UNION SELECT '张三', 'SQL', 95 UNION SELECT '李四', '.net', 86 UNION SELECT '李四', 'java', 92 UNION SELECT '王五', '.net', 96 UNION SELECT '王五', 'java', 88 UNION SELECT '王五', 'SQL', 78 select name,[.net],[java],[sql] from tbc pivot (max(score) for sub in([.net],[java],sql)) as d name .net java sql 李四 86 92 NULL 王五 96 88 78 张三 80 85 95