select column_name,
<aggregation function>(<case when expression>)
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
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>
非聚合列。
[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