把行資料變成列資料的SQL查詢

2022-03-06 00:58:19 字數 1453 閱讀 9855

group by 子句

指定用來放置輸出行的組,並且如果 select 子句 中包含聚合函式,則計算每組的彙總值。指定 group by 時,選擇列表中任一非聚合表示式內的所有列都應包含在 group by 列表中,或者 group by 表示式必須與選擇列表表示式完全匹配。

即select選擇的列要麼在聚合函式中,要麼在group by 中進行分組。

如果你想按下面的方式顯示資料

而你的資料庫中實際的儲存方式是如下的。即是以行的形式儲存的資料,現在要變成上面的列來儲存

sql可以如下:

select s.classprocode,s.yearmonth,

max(case s.surveycode when 'sc001' then s.score else 0 end) as '報名報道',

max(case s.surveycode when 'sc002' then s.score else 0 end) as '後勤接待',

max(case s.surveycode when 'sc003' then s.score else 0 end) as '副班主任'

from sersurvey s

group by s.classprocode,s.yearmonth

--備註:按照surveycode這個條件來轉換資料,如果條件成立,則轉換score這一行的資料成列顯示,否則為0

或者 select a.*,

(select top 1 score from sersurvey

where classprocode = a.classprocode and yearmonth = a.yearmonth and surveycode = 'sc001') as '報名報道',

(select top 1 score from sersurvey

where classprocode = a.classprocode and yearmonth = a.yearmonth and surveycode = 'sc002') as '後勤接待',

(select top 1 score from sersurvey

where classprocode = a.classprocode and yearmonth = a.yearmonth and surveycode = 'sc003') as '副班主任'

from

(select s.classprocode,s.yearmonth

from  sersurvey s

group by s.classprocode,s.yearmonth

) a可以分頁的:

把列變成行的sql語句

現有如下表 科目 分數 姓名 語文 88 董兆 數學 95 董兆 英語 89 董兆 語文 69 嬋娟 數學 95 嬋娟 英語 89 嬋娟 語文 69 李慧 數學 95 李慧 英語 89 李慧 一條sql語句,查詢結果是 李慧 嬋娟 董兆 語文 69 69 88 數學 95 95 95 英語 89 8...

讓查詢資料由行變成列

有這樣兩個資料表 wuzi table 物資編碼 id 顏色編號 color id 數量 acount 1111 1 10 2222 2 20 1111 1 20 3333 3 5 1111 3 10 yanse table 顏色編號 color id 顏色名稱 color 1 紅色2 蘭色3 綠色...

資料庫查詢行數 簡單查詢 如何提高SQL查詢的效率

1.selelct語句中盡量避免使用 需要哪些列的資料,就提取哪些列的資料,盡量少用 來獲取資料 2.where字句比較符號左側避免使用函式 導致資料庫引擎進行全表掃瞄,從而增加執行行時間 考慮將其移到比較運算子右側 3.盡量避免使用in和not in 也會導致資料庫進行全表搜尋,增加執行時間,部分...