这是我的表格
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)
)
表课程
Cno Cname
------------
C001 Math
C002 CS
C003 Database
表格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
但如果我使用"由Course.Cno"组合,则无法工作..
为什么我必须添加" Cname,Semester"?
我试过mysql working..but sql server 2012 not。
答案 0 :(得分:0)
使用子查询来获取计数:
select Cno, Cname, (select count(*) from sc where c.cno = sc.cno) as cnt
from Course as c
order by cnt