SQL 多列多表分组
SQL Group By Multiple columns & multiple tables
这是我的 tables
CREATE TABLE Course(Cno CHAR(6), Cname NVARCHAR(20) NOT NULL,PRIMARY KEY(Cno))
CREATE TABLE SC(Sno CHAR(7) NOT NULL,Cno CHAR(6) NOT NULL,Grade TINYINT,
PRIMARY KEY(Sno, Cno),
FOREIGN KEY(Sno) REFERENCES Student(Sno),
FOREIGN KEY(Cno) REFERENCES Course(Cno)
)
table 课程
Cno Cname
------------
C001 Math
C002 CS
C003 Database
table SC
Sno Cno Grade
-------------------
1 C001 80
2 C002 90
2 C003 70
3 C002 60
想要...:
Cno Cname Number
-----------------------
C002 CS 2
C001 Math 1
C003 Database 1
此代码有效
select top 3 with ties Course.Cno, Course.Cname, count(SC.Cno) AS Number
from Course left join SC
on Course.Cno = SC.Cno
group by Course.Cno, Cname, Semester
order by count(SC.Cno) desc
但如果我使用 "goup by Course.Cno",则无效..
为什么我必须添加 "Cname, Semester"?
我试过 mysql 成功了..但是 sql 服务器 2012 不行。
使用子查询获取计数:
select Cno, Cname, (select count(*) from sc where c.cno = sc.cno) as cnt
from Course as c
order by cnt
这是我的 tables
CREATE TABLE Course(Cno CHAR(6), Cname NVARCHAR(20) NOT NULL,PRIMARY KEY(Cno))
CREATE TABLE SC(Sno CHAR(7) NOT NULL,Cno CHAR(6) NOT NULL,Grade TINYINT,
PRIMARY KEY(Sno, Cno),
FOREIGN KEY(Sno) REFERENCES Student(Sno),
FOREIGN KEY(Cno) REFERENCES Course(Cno)
)
table 课程
Cno Cname
------------
C001 Math
C002 CS
C003 Database
table SC
Sno Cno Grade
-------------------
1 C001 80
2 C002 90
2 C003 70
3 C002 60
想要...:
Cno Cname Number
-----------------------
C002 CS 2
C001 Math 1
C003 Database 1
此代码有效
select top 3 with ties Course.Cno, Course.Cname, count(SC.Cno) AS Number
from Course left join SC
on Course.Cno = SC.Cno
group by Course.Cno, Cname, Semester
order by count(SC.Cno) desc
但如果我使用 "goup by Course.Cno",则无效..
为什么我必须添加 "Cname, Semester"?
我试过 mysql 成功了..但是 sql 服务器 2012 不行。
使用子查询获取计数:
select Cno, Cname, (select count(*) from sc where c.cno = sc.cno) as cnt
from Course as c
order by cnt