SQLServer之行數據轉換爲列數據

準備工做

建立表

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,
<aggregation function>(<case when expression>)  
from database.schema.table
group by column_name

語法解析

column_namehtml

數據列列名html5

aggregation functionandroid

聚合函數,常見的有:sum,max,min,avg,count等。ios

case when expressionexpress

case when表達式ide

示例

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

示例結果

轉換前函數

clipboard.png

轉換後spa

clipboard.png

使用PIVOT進行行專列

PIVOT經過將表達式中一列中的惟一值轉換爲輸出中的多個列來旋轉表值表達式。並PIVOT在最終輸出中須要的任何剩餘列值上運行聚合,PIVOT提供比一系列複雜的SELECT...CASE語句指定的語法更爲簡單和可讀的語法,PIVOT執行聚合並將可能的多行合併到輸出中的單個行中。.net

語法

select <non-pivoted column>,  
    [first pivoted column] as <column name>,  
    [second pivoted column] as <column name>,  
    ...  
    [last pivoted column] as <column name>  
from  
    (<select query that produces the data>)   
    as <alias for the source query>  
pivot  
(  
    <aggregation function>(<column being aggregated>)  
for   
[<column that contains the values that will become column headers>]   
    in ( [first pivoted column], [second pivoted column],  
    ... [last pivoted column])  
) as <alias for the pivot table>  
<optional order by clause>;

語法解析

<non-pivoted column>code

非聚合列。

[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>

排序規則。

示例

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

示例結果

轉換前

clipboard.png

轉換後

clipboard.png

注意事項

一、若是輸出列名不能在錶轉換列中,則不會執行任何計算。

二、輸出的全部列的列名的數據類型必須一致。

相關文章
相關標籤/搜索