首先是三張表, CNo對(duì)應(yīng)的是課程,在這里我就粘貼了。
主表
人名表
按照常規(guī)查詢
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
那么結(jié)果是這樣的
但是這是橫表 不是我想看到的結(jié)果。
我們要看到這樣的結(jié)果:
那么怎么辦呢?
第一種寫法:
復(fù)制代碼 代碼如下:
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 '數(shù)學(xué)',
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
第二種寫法:
復(fù)制代碼 代碼如下:
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 '數(shù)學(xué)',
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
這是我工作遇到過得情況,總結(jié)下來。如果有遇到這種情況的話可以參考下。
您可能感興趣的文章:- SQL Server縱表與橫表相互轉(zhuǎn)換的方法