不常用sql語句備份

1.行轉列

case 需要轉換字段 when(判斷相等關係) 待判斷的值 then 相等時填充的值 else 不相等時填充的值 end
轉換結束
使用場景:通常跟分組,聚合函數連用
表:stu_score
stu_id subject score
sql:select stu_id,sum(case subject when ‘數學’ then score else 0 end) math from stu_score group by stu_id

2.分組生成排序編號字段

row_number()over(partition by 分組依據列表 order by 排序依據列表 倒序/順序)
使用場景:分組後需得到每組的前幾項
注意:生成的編號不能直接用於where子句 需轉臨時表
表:stu_score
stu_id subject score
sql:select t.* from
(select stu_score.*,row_number()over(partition by subject order by subject,score desc) id) t
where id<=2

發佈了43 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章