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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM