sqlserver中查詢橫表變豎表的sql語句簡析。本站提示廣大學習愛好者:(sqlserver中查詢橫表變豎表的sql語句簡析)文章只能為提供參考,不一定能成為您想要的結果。以下是sqlserver中查詢橫表變豎表的sql語句簡析正文
主表
人名表
依照慣例查詢
SELECT s.SName, c.CName,s2.SCgrade
FROM S s INNER JOIN SC s2 ON s2.SNo = s.SNo INNER JOIN C c ON c.CNo = s2.CNo
那末成果是如許的
然則這是橫表 不是我想看到的成果。
我們要看到如許的成果:
那末怎樣辦呢?
第一種寫法:
SELECT w.SName,
sum(case when w.CNo= 1 then w.SCgrade ELSE 0 END) AS '語文',
sum(case WHEN w.CNo =2 THEN w.SCgrade ELSE 0 END) AS '數學',
sum(case when w.CNo= 3 then w.SCgrade ELSE 0 END) AS '英語'
FROM
(SELECT s.SNo,s.SName, s2.CNo, s2.SCgrade FROM s s INNER JOIN SC s2 ON s2.SNo = s.SNo WHERE s.SNo IN (SELECT c.SNo FROM sc c GROUP BY c.SNo ))
AS w GROUP BY w.SName
第二種寫法:
SELECT s.SName,
sum(case when s2.CNo= 1 then s2.SCgrade ELSE 0 END) AS '語文',
sum(case WHEN s2.CNo =2 THEN s2.SCgrade ELSE 0 END) AS '數學',
sum(case when s2.CNo= 3 then s2.SCgrade ELSE 0 END) AS '英語'
FROM
S s INNER JOIN SC s2 ON s2.SNo = s.SNo
INNER JOIN C c ON c.CNo = s2.CNo
GROUP BY s.SNo,
s.SName
這是我任務碰到過得情形,總結上去。假如有碰到這類情形的話可以參考下。