sqlserver中查询横表变竖表的sql语句简析
更新时间:2012年05月10日 21:30:12 作者:
SQL 查询横表变竖表是我工作遇到过得情况,总结下来。如果有遇到这种情况的话可以参考下
首先是三张表, 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
这是我工作遇到过得情况,总结下来。如果有遇到这种情况的话可以参考下。
主表
人名表
按照常规查询
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
这是我工作遇到过得情况,总结下来。如果有遇到这种情况的话可以参考下。
您可能感兴趣的文章:
相关文章
sql server 2000阻塞和死锁问题的查看与解决方法
在实际引用当中,数据库阻塞和死锁在程序开发过程经常出现,下面通过介绍数据库阻塞和数据库死锁,并提供查看和解决阻塞和死锁的方法2014-01-01
最新评论