Sql Server 行转列的多种写法
来源:互联网 发布:格斗术软件 编辑:程序博客网 时间:2024/06/05 02:06
if not object_id('Class') is nulldrop table ClassGoCreate table Class([Student] nvarchar(2),[Course] nvarchar(2),[Score] int)Insert Classselect N'张三',N'语文',78 union allselect N'张三',N'数学',87 union allselect N'张三',N'英语',82 union allselect N'张三',N'物理',90 union allselect N'李四',N'语文',65 union allselect N'李四',N'数学',77 union allselect N'李四',N'英语',65 union allselect N'李四',N'物理',85Goselect * from classGO/******************************************* * 第一种写法 *用静态脚本 *******************************************/selectstudent--通过Case When 实现行转列功能,max(case [Course] when '数学' then Score else 0 end) as [数学],max(case [Course] when '物理' then Score else 0 end) as [物理],max(case [Course] when '英语' then Score else 0 end) as [英语],max(case [Course] when '语文' then Score else 0 end) as [语文],sum(Score) as sum_socre,avg(Score) as avg_Scorefrom classgroup by studentGo/******************************************* *第二种写法 *动态脚本,行转列。 *******************************************/declare @sql nvarchar(max);declare @i int;set @sql = ''set @i = 1select @sql = @sql + ',max(case when [Course]=''' + [Course] +'''' + ' then [Score] end) as '+[Course]+'', @i = @i + 1from class group by [Course]set @sql = 'select [Student]' + @sql + ' from classgroup by [Student]'exec(@sql)/******************************************* * 第三种写法: * 用Pivot静态脚本,通过Pivot功能实现行转列语法:table_sourcePIVOT(聚合函数(value_column)FOR pivot_columnIN(<column_list>) *******************************************/selectStudent,[语文],[数学],[英语],[物理]from Classpivot(max(Score) for Course in([语文],[数学],[英语],[物理]))TGO/******************************************* * 第四种写法: * pivot 动态脚本 *******************************************/declare @sql varchar(max)select @sql=ISNULL(@sql+',','')+quotename(Course)from Classgroup by Courseexec('select * from Classpivot(max(Score) for Course in ('+@sql+'))T')go
0 0
- Sql Server 行转列的多种写法
- sql语句的多种写法
- 变量的多种写法
- 一句话的多种写法
- listener的多种写法
- 数组的多种写法
- SQL SERVER分页的一般写法
- SQL Server中触发器的写法
- SQL Server死锁监控的语句写法
- SQL SERVER存储过程的写法
- 一句话木马的多种写法
- 冒泡排序的多种写法
- 折半查找的多种写法
- main函数的多种写法
- QT connect的多种写法
- js函数的多种写法
- SQL Server 数据库中行变列的SQL语句写法
- SQL Server日期格式的多种转换方法
- 配置Spring数据源
- 出租车计费(C语言)
- HDU 4925 Apple Tree
- HDOJ 题目2709Sumsets(递推)
- BigDecimal和Int类型的转换以及BigDecimal类型的运算
- Sql Server 行转列的多种写法
- Linux静态库(含依赖库)实战与简析
- java反射的学习
- JNI NDK ANDROID
- web项目页面数据量太大容易奔溃问题
- 最大熵模型进行中文分词
- debian mysql 定时自动备份的脚本
- CENTOS 6.5 配置YUM安装NGINX
- 网络数据传递之 Json数据解析