資料庫行列轉換
實現只顯示為某值的欄位,可以通過行列轉換實現。
以下是以sql server為例來說明:
select b.stu_name,
max(case a.subject when '語文' then a.grade else '' end) as 語文,
max(case a.subject when '數學' then a.grade else '' end) as 數學,
max(case a.subject when '英語' then a.grade else '' end) as 英語
from stu_grade a,stu_master b
where a.stu_no=b.stu_no
group by b.stu_name
資料庫為oralce的話執行
select b.stu_name,
max(case a.subject when '語文' then to_char(a.grade) else '' end) as 語文,
max(case a.subject when '數學' then to_char(a.grade) else '' end) as 數學,
max(case a.subject when '英語' then to_char(a.grade) else '' end) as 英語
from stu_grade a,stu_master b
where a.stu_no=b.stu_no
group by b.stu_name
⑵ 寫sql,怎麼將查詢結果的行列轉換呀
有意思的問題 給出一個參考的URL: 假設你表是這樣的結構部件 入庫日期 入庫數量 A 1/1 10 A 1/1 5 A 1/2 10 B 1/5 10 其實就是兩種方法,假設你的資料庫是11以前的,只能先定義好查哪天到哪天 然後那麼 selct 部件, sum( decode(入庫日期=1號,入庫數量,0), sum( decode(入庫日期=2號,入庫數量,0), 以此類推 from 入庫表 group BY 部件(原理上就是將不是這天的變成0,再合計)要是Oracle資料庫是11的話,就簡單了,直接pivot搞定 pivot語法就不說了,網上一堆一堆的 ~