2017-09-15 35 views
0

我有这三个表:的SQL Server:查询得到多数学校与作曲家的歌曲

create table musicSchool 
(
    schoolId numeric(2) not null, 
    name  varchar(30) not null, 
    city  varchar(20) not null 
) 

create table Composer 
(
    composerId numeric(4) not null, 
    name  varchar(20) not null, 
    birthday datetime null, 
    schoolId numeric(2) null 
) 

create table Song 
(
    songnumber numeric(5) not null, 
    composerId numeric(4) not null, 
    title  varchar(20) not null, 
    year  numeric(4) not null 
) 

现在我想在学校或学校最作曲的歌曲。

SELECT 
    M.name, COUNT(M.name) 
FROM 
    musicSchool M 
INNER JOIN 
    Composer C ON M.schoolId = C.schoolId 
INNER JOIN 
    Song S ON C.composerId= S.composerId 
GROUP BY 
    M.name 

我与他们的作曲家的歌曲总数的学校,但我想与作曲家的歌曲最多的学校/学院。

感谢您的帮助!

+2

这是一个基本的连接练习。这里不需要存在和子查询。只需内部连接和基本聚合。提示,看看COUNT。 –

+0

应用表格作曲和歌曲之间的连接,然后通过musicSchool表格中的“any”进行检查 –

+0

乍一看,这似乎是一个“关系分裂”问题。做一个谷歌搜索SQL Server关系部门... https://www.google.com/search?q=sql+server+relational+division&rlz=1C1ASUC_enUS560US561&oq=sql+server+relational+division&aqs=chrome..69i57.7575j0j7&sourceid = chrome&ie = UTF-8 –

回答

4

您使用TOP获取仅最上面的记录。

SELECT TOP(1) WITH TIES 
    M.name, COUNT(M.name) as SongCount 
FROM 
    musicSchool M 
INNER JOIN 
    Composer C ON M.schoolId = C.schoolId 
INNER JOIN 
    Song S ON C.composerId= S.composerId 
GROUP BY 
    M.name 
ORDER BY SongCount DESC 
+0

我总是忘记与关系。从我+1 – scsimon

1

cte和派生表的简单方法。

with cte as(
    SELECT 
     M.name, 
     CT = COUNT(s.songnumber) 
    FROM 
     musicSchool M 
    INNER JOIN 
     Composer C ON M.schoolId = C.schoolId 
    INNER JOIN 
     Song S ON C.composerId= S.composerId 
    GROUP BY 
     M.name) 

select c.* 
from cte c 
inner join 
    (select CT = max(ct) from cte) c2 on c2.CT = c.CT