首先是三張表, CNo對應的是課程,在這裡我就粘貼了。
主表
人名表
按照常規查詢
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
這是我工作遇到過得情況,總結下來。如果有遇到這種情況的話可以參考下。