今天就跟大家聊聊有关SQL Server中怎么将行数据转换为列数据,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

准备工作

创建表

use[test1]gocreatetable[dbo].[student]([id][int]identity(1,1)notnull,[name][nvarchar](50)null,[project][nvarchar](50)null,[score][int]null,constraint[pk_student]primarykeyclustered([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

插入数据

insertintotest1.dbo.student(name,project,score)values('张三','android','60'),('张三','ios','70'),('张三','html5','55'),('张三','.net','100'),('李四','android','60'),('李四','ios','75'),('李四','html5','90'),('李四','.net','100');

使用Case When和聚合函数进行行专列

语法

selectcolumn_name,<aggregationfunction>(<casewhenexpression>)fromdatabase.schema.tablegroupbycolumn_name

语法解析

column_name

数据列列名

aggregation function

聚合函数,常见的有:sum,max,min,avg,count等。

case when expression

case when表达式

示例

selectname,max(caseprojectwhen'android'thenscoreend)as'安卓',max(caseprojectwhen'ios'thenscoreend)as'苹果',max(caseprojectwhen'html5'thenscoreend)as'html5',max(caseprojectwhen'.net'thenscoreend)as'.net'from[test1].[dbo].[student]groupbyname

示例结果

转换前

转换后

使用PIVOT进行行专列

PIVOT通过将表达式中一列中的唯一值转换为输出中的多个列来旋转表值表达式。并PIVOT在最终输出中需要的任何剩余列值上运行聚合,PIVOT提供比一系列复杂的SELECT...CASE语句指定的语法更为简单和可读的语法,PIVOT执行聚合并将可能的多行合并到输出中的单个行中。

语法

select<non-pivotedcolumn>,[firstpivotedcolumn]as<columnname>,[secondpivotedcolumn]as<columnname>,...[lastpivotedcolumn]as<columnname>from(<selectquerythatproducesthedata>)as<aliasforthesourcequery>pivot(<aggregationfunction>(<columnbeingaggregated>)for[<columnthatcontainsthevaluesthatwillbecomecolumnheaders>]in([firstpivotedcolumn],[secondpivotedcolumn],...[lastpivotedcolumn]))as<aliasforthepivottable><optionalorderbyclause>;

语法解析

<non-pivoted column>

非聚合列。

[first pivoted column]

第一列列名。

[second pivoted column]

第二列列名。

[last pivoted column]

最后一列列名。

<select query that produces the data>

数据子表。

<alias for the source query>

表别名。

<aggregation function>

聚合函数。

<column being aggregated>

聚合函数列,用于输出值列,最终输出中返回的列(称为分组列)将对其进行分组。

[<column that contains the values that will become column headers>]

转换列,此列返回的唯一值将成为最终结果集中的字段。

[first pivoted column], [second pivoted column], ... [last pivoted column]

数据行中每一行行要转换的列名。

<optional order by clause>

排序规则。

示例

selectb.Name,b.[android],b.[ios],b.[html5],b.[.net]from(selectName,Project,Scorefrom[test1].[dbo].[student])asapivot(max(Score)forProjectin([android],[ios],[html5],[.net]))asborderbyb.namedesc

1、如果输出列名不能在表转换列中,则不会执行任何计算。

2、输出的所有列的列名的数据类型必须一致。

看完上述内容,你们对SQL Server中怎么将行数据转换为列数据有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。