最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
SQL Server基础之行数据转换为列数据方法
时间:2022-06-29 09:07:15 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下SQL Server基础之行数据转换为列数据方法,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
准备工作
创建表
use [test1] go create table [dbo].[student]( [id] [int] identity(1,1) not null, [name] [nvarchar](50) null, [project] [nvarchar](50) null, [score] [int] null, constraint [pk_student] primary key clustered ( [id] asc )with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary] ) on [primary] go
插入数据
insert into test1.dbo.student(name,project,score) values('张三','android','60'), ('张三','ios','70'), ('张三','html5','55'), ('张三','.net','100'), ('李四','android','60'), ('李四','ios','75'), ('李四','html5','90'), ('李四','.net','100');
使用Case When和聚合函数进行行专列
语法
select column_name,( ) from database.schema.table group by column_name
语法解析
column_name
数据列列名
aggregation function
聚合函数,常见的有:sum,max,min,avg,count等。
case when expression
case when表达式
示例
select name, max(case project when 'android' then score end) as '安卓', max(case project when 'ios' then score end) as '苹果', max(case project when 'html5' then score end) as 'html5', max(case project when '.net' then score end) as '.net' from [test1].[dbo].[student] group by name
示例结果
转换前
转换后
使用PIVOT进行行专列
PIVOT通过将表达式中一列中的唯一值转换为输出中的多个列来旋转表值表达式。并PIVOT在最终输出中需要的任何剩余列值上运行聚合,PIVOT提供比一系列复杂的SELECT...CASE语句指定的语法更为简单和可读的语法,PIVOT执行聚合并将可能的多行合并到输出中的单个行中。
语法
select, [first pivoted column] as , [second pivoted column] as , ... [last pivoted column] as from (
语法解析
非聚合列。
[first pivoted column]
第一列列名。
[second pivoted column]
第二列列名。
[last pivoted column]
最后一列列名。
数据子表。
表别名。
聚合函数。
聚合函数列,用于输出值列,最终输出中返回的列(称为分组列)将对其进行分组。
[
转换列,此列返回的唯一值将成为最终结果集中的字段。
[first pivoted column], [second pivoted column], ... [last pivoted column]
数据行中每一行行要转换的列名。
排序规则。
示例
select b.Name,b.[android],b.[ios],b.[html5],b.[.net] from (select Name,Project,Score from [test1].[dbo].[student]) as a pivot ( max(Score) for Project in ([android],[ios],[html5],[.net]) ) as b order by b.name desc
示例结果
转换前
转换后
注意事项
1、如果输出列名不能在表转换列中,则不会执行任何计算。
2、输出的所有列的列名的数据类型必须一致。
相关文章
- 沙丘觉醒怎么饮血快速解渴 饮血解渴方法介绍 07-15
- 最终幻想14水晶世界居格斯怎么打 强腕的居格斯打法分享 07-15
- 沙丘觉醒怎么更改哈克南厄崔迪家族阵营 阵营转换方法 07-15
- 欧易app注册下载 欧易app交易所v6.7.0 07-15
- 剑星乌龙谷物茶饮料罐在哪 乌龙谷物茶饮料罐收集位置一览 07-15
- 幻兽帕鲁熔岩兽出没地点 帕鲁熔岩兽捕捉位置介绍 07-15