SQL 常用脚本

1、行转列

例子:成绩表有姓名,月份,成绩,要生成左边的效果

CREATE TABLE StudentScore(NAME NVARCHAR(10),months NVARCHAR(10),score INT)
INSERT INTO  StudentScore VALUES('张三','一月',85)
INSERT INTO  StudentScore VALUES('张三','二月',97)
INSERT INTO  StudentScore VALUES('李四','一月',77)
INSERT INTO  StudentScore VALUES('李四','二月',86)
INSERT INTO  StudentScore VALUES('王五','一月',86)
INSERT INTO  StudentScore VALUES('王五','二月',88)
INSERT INTO  StudentScore VALUES('李白','二月',90)

-- 静态SQL,指月份只有一月和二月

--方法一:
SELECT  NAME AS 姓名,
 MAX(CASE months WHEN '一月' THEN score ELSE 0 END) 一月,
 MAX(CASE months WHEN '二月' THEN score ELSE 0 END) 二月
FROM StudentScore
GROUP BY name
   
    
--方法二(SQL Server2005 以上版本支持):
select * from StudentScore 
pivot (
max(score) /*行转列后 列的值*/
for months /*需要行转列的列*/ in (一月,二月) ) /*列的值*/
b



--动态SQL,指月份不止一月和二月
--方法一:
declare @sql varchar(8000)
set @sql = 'select name '
select @sql = @sql + ' , max(case months when ''' + months + ''' then score else 0 end) [' + months + ']'
from (select distinct months from StudentScore) as a
set @sql = @sql + ' from StudentScore group by name'
exec(@sql) 


--方法二(SQL Server2005 以上版本支持):
declare @sqla varchar(8000)
select @sqla = isnull(@sqla + ',' , '') + months from StudentScore group by months
exec ('select * from StudentScore pivot (max(score) for months in (' + @sqla + ')) b')

猜你喜欢

转载自blog.csdn.net/u012110480/article/details/84326290