准備工作
創建表
1 use [test1]
2 go
3
4 create table [dbo].[student]( 5 [id] [int] identity(1,1) not null, 6 [name] [nvarchar](50) null, 7 [project] [nvarchar](50) null, 8 [score] [int] null, 9 constraint [pk_student] primary key clustered
10 ( 11 [id] asc
12 )with (pad_index = off, statistics_norecompute = off, ignore_dup_key = off, allow_row_locks = on, allow_page_locks = on) on [primary]
13 ) on [primary]
14 go
插入數據
1 insert into test1.dbo.student(name,project,score) 2 values('張三','android','60'), 3 ('張三','ios','70'), 4 ('張三','html5','55'), 5 ('張三','.net','100'), 6 ('李四','android','60'), 7 ('李四','ios','75'), 8 ('李四','html5','90'), 9 ('李四','.net','100');
使用Case When和聚合函數進行行專列
語法
1 select column_name, 2 <aggregation function>(<case when expression>) 3 from database.schema.table 4 group by column_name
語法解析
column_name
數據列列名
aggregation function
聚合函數,常見的有:sum,max,min,avg,count等。
case when expression
case when表達式
示例
1 select name, 2 max(case project when 'android' then score end) as '安卓', 3 max(case project when 'ios' then score end) as '蘋果', 4 max(case project when 'html5' then score end) as 'html5', 5 max(case project when '.net' then score end) as '.net'
6 from [test1].[dbo].[student]
7 group by name
示例結果
轉換前

轉換后

使用PIVOT進行行專列
PIVOT通過將表達式中一列中的唯一值轉換為輸出中的多個列來旋轉表值表達式。並PIVOT在最終輸出中需要的任何剩余列值上運行聚合,PIVOT提供比一系列復雜的SELECT...CASE語句指定的語法更為簡單和可讀的語法,PIVOT執行聚合並將可能的多行合並到輸出中的單個行中。
語法
1 select <non-pivoted column>, 2 [first pivoted column] as <column name>, 3 [second pivoted column] as <column name>, 4 ... 5 [last pivoted column] as <column name> 6 from 7 (<select query that produces the data>) 8 as <alias for the source query> 9 pivot 10 ( 11 <aggregation function>(<column being aggregated>) 12 for 13 [<column that contains the values that will become column headers>] 14 in ( [first pivoted column], [second pivoted column], 15 ... [last pivoted column]) 16 ) as <alias for the pivot table> 17 <optional order by clause>;
語法解析
<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>
排序規則。
示例
1 select b.Name,b.[android],b.[ios],b.[html5],b.[.net]
2 from
3 (select Name,Project,Score from [test1].[dbo].[student]) 4 as a 5 pivot 6 ( 7 max(Score) 8 for Project in ([android],[ios],[html5],[.net]) 9 ) 10 as b 11 order by b.name desc
示例結果
轉換前

轉換后

注意事項
1、如果輸出列名不能在表轉換列中,則不會執行任何計算。
2、輸出的所有列的列名的數據類型必須一致。
