sqlserver行转列 pivot

 

PIVOT函数的格式如下

PIVOT(<聚合函数>([聚合列值]) FOR [行转列前的列名] IN([行转列后的列名1],[行转列后的列名2],[行转列后的列名3],.......[行转列后的列名N]))

    <聚合函数>就是我们使用的SUM,COUNT,AVG等Sql聚合函数,也就是行转列后计算列的聚合方式。
    [聚合列值]要进行聚合的列名
    [行转列前的列名]这个就是需要将行转换为列的列名。
    [行转列后的列名]这里需要声明将行的值转换为列后的列名,因为转换后的列名其实就是转换前行的值,所以上面格式中的[行转列后的列名1],[行转列后的列名2],[行转列后的列名3],......[行转列后的列名N]其实就是[行转列前的列名]每一行的值

 

查询表数据如图,查询每门分数都大于80分的人姓名:

 
1)用exist关键字查询

select distinct name from Table_CourseNum a
where exists(select 1 from Table_CourseNum where name=a.name and course='语文' and num>80)
and exists(select 1 from Table_CourseNum where name=a.name and course='数学' and num>80)
and exists(select 1 from Table_CourseNum where name=a.name and course='英语' and num>80)


2)第一种方法感觉比较偏,有想过用partition by分组排序函数

select * from
(
select ROW_NUMBER() over(partition by Name order by num desc) cnt,* from Table_CourseNum where num>80
) a
where a.cnt=(select count(0) from (select distinct course from Table_CourseNum) t)
--和下边写法差不多
select * from
(
select name,count(0) cnt from Table_CourseNum where num>80 group by name
) a
where a.cnt>=(select count(0) from (select distinct course from Table_CourseNum) t)


3)第三种写法就行转列了

select * from (
select * from Table_CourseNum
pivot(sum(num) for course in ([语文],[数学],[英语])) t
) a where 语文>80 and 数学>80 and 英语>80


参考partitionby:https://www.cnblogs.com/zhangchengye/p/5473860.html
参考pivot:https://www.cnblogs.com/net-study/p/10396368.html

posted @ 2020-11-02 18:36  户的博客  阅读(1665)  评论(0编辑  收藏  举报