所以我有3个表连接在一起,名为office,employee和dependent。
办公室:Oid(PK),officeName
员工:EID(PK),Fname,Lname,JobTitle,薪水,DOH,性别,DOB,OID(FK1),主管(FK2)
依赖:DID(PK),Fname,Lname,性别,EID(FK1)
以下是表格图片的链接: http://classweb2.mccombs.utexas.edu/mis325/class/hw/hw12a.jpg
我需要显示5名员工的连锁姓名和EID以及最大数量的家属,如果有五个最大的并列,那么我需要显示所有搭售员工。
我对如何开始感到困惑。请帮忙 :) 提前谢谢你
答案 0 :(得分:0)
解决问题:
EID有多少家属:
SELECT EID, COUNT(*) AS C
FROM Dependent
GROUP BY EID
添加排名
SELECT EID, C, RANK() OVER (ORDER BY C DESC)
FROM (
SELECT EID, COUNT(*) AS C
FROM Dependent
GROUP BY EID
) S
我们想要前5个
SELECT EID
FROM (
SELECT EID, C, RANK() OVER (ORDER BY C DESC) AS R
FROM (
SELECT EID, COUNT(*) AS C
FROM Dependent
GROUP BY EID
) S
) S2
WHERE R <= 5
现在问你想要什么:
SELECT * -- or whatever
FROM Employee
WHERE EID IN (
SELECT EID
FROM (
SELECT EID, C, RANK() OVER (ORDER BY C DESC) AS R
FROM (
SELECT EID, COUNT(*) AS C
FROM Dependent
GROUP BY EID
) S
) S2
WHERE R <=5
) S3
我建议你运行每一步,确保它能为你提供预期的结果。
答案 1 :(得分:-1)
嗯,我会尝试这样的事情:
Select TOP 5
a.FNAME,
a.LNAME,
a.EID,
Count(b.EID) as Dependents
FROM employee a
LEFT JOIN dependent b on a.EID = b.EID
group by 1,2,3 order by Dependents desc