我是SQL新手,我目前正在尝试学习如何在Visual Studio中制作报表。我需要制作一张桌子,图表和其他一些东西。我决定将矩阵作为最后一部分,现在我被卡住了。我在SQL Server中编写查询。
我有两个表:Staff(empID,StaffLevel,Surname)和WorkOfArt(artID,name,curator,helpingCurator)。在Curator和HelpingCurator列中,我使用了empID中的数字。
我喜欢我的矩阵,以显示每个empID和他们作为策展人的绘画数量以及他们作为帮助策展人的绘画数量(所以我想要三列:empID,count(策展人),count(helpsCurator)。
Select Staff.empID, count(WorkOfArt.Curator) as CuratorTotal
FROM Staff, WorkOfArt
WHERE Staff.empID=WorkOfArt.Curator
and Staff.StaffLevel<7
group by Staff.empID;
Select Staff.empID, count(WorkOfArt.HelpingCurator) as HelpingCuratorTotal
FROM Staff, WorkOfArt
WHERE Staff.empID=WorkOfArt.HelpingCurator
and Staff.StaffLevel<7
group by Staff.empID;
我创建了这两个查询并且它们工作得很好,但我需要在一个查询中。
我试过了:
Select Staff.empID, count(WorkOfArt.Curator) as CuratorTotal,
COUNT(WorkOfArt.HelpingCurator) as HelpingCuratorTotal
FROM Staff FULL OUTER JOIN WorkOfArt on Staff.empID=WorkOfArt.Curator
and Staff.empID=WorkOfArt.HelpingCurator
WHERE Staff.StaffLevel<7
group by Staff.empID;
(以及使用左外连接或右外连接) - 这个给了我一个带有empID的表,但在两个count列中只有0 - 和:
Select Staff.empID, count(WorkOfArt.Curator) as CuratorTotal,
COUNT(WorkOfArt.HelpingCurator) as HelpingCuratorTotal
FROM Staff, WorkOfArt
WHERE Staff.empID=WorkOfArt.Curator
and Staff.empID=WorkOfArt.HelpingCurator
and Staff.StaffLevel<7
group by Staff.empID;
这个只给我列的名字。
我不知道下一步该做什么。我试图在谷歌找到答案,但我发现的所有解释对我来说都更为先进,所以我无法理解他们......你能帮助我吗?提示也很好。
答案 0 :(得分:4)
最简单的方法是使用select子句中的内部选择,这很可能是这样的:
Select
S.empID,
(select count(*) from WorkOfArt C where C.Curator = S.empID)
as CuratorTotal,
(select count(*) from WorkOfArt H where H.HelpingCurator = S.empID)
as HelpingCuratorTotal
FROM Staff S
WHERE S.StaffLevel<7
group by S.empID;
这样,具有不同角色的行不会导致计算出现问题。如果表格非常大或者您有很多不同的角色,那么在WorkOfArt表中首先对项目进行分组的更复杂查询可能会有更好的性能,因为这需要两次读取行。
答案 1 :(得分:1)
从性能角度来看,以下查询可能更有效率
select e.EmpId, CuratorForCount, HelpingCuratorForCount
from Staff s
inner join ( select Curator, count(*) as CuratorForCount
from WorkOfArt
group by Curator) mainCurator on s.EmpId = mainCurator.Curator
inner join ( select HelpingCurator, count(*) as HelpingCuratorForCount
from WorkOfArt
group by HelpingCurator) secondaryCurator on s.EmpId = secondaryCurator.HelpingCurator
答案 2 :(得分:1)
如果您希望从WorkOfArt
表中获取多个值聚合值,则可以使用一种方法来预先聚合结果:
Select s.empID, COALESCE(woac.cnt, 0) as CuratorTotal,
COALESCE(woahc.cnt) as HelpingCuratorTotal
FROM Staff s LEFT JOIN
(SELECT woa.Curator, COUNT(*) as cnt
FROM WorkOfArt woa
GROUP BY woa.Curator
) woac
ON s.empID = woac.Curator LEFT JOIN
(SELECT woa.HelpingCurator, COUNT(*) as cnt
FROM WorkOfArt woa
GROUP BY woa.HelpingCurator
) woahc
ON s.empID = woahc.HelpingCurator
WHERE s.StaffLevel < 7;
请注意,不需要外层的聚合。