我有一个奇怪的情况,不太确定如何接近它。
我有2个单独的表格:
表A是提交
id
submitterQID
nomineeQID
story
表B是员工
QID
Name
Department
我试图获得按部门分组的提交总数以及提名总数。
这就是我的存储过程:
BEGIN
SELECT TOP 50 count(A.[nomineeQID]) AS totalNominations,
count(A.[subQID]) AS totalSubmissions,
B.[DepartmentDesc] AS department
FROM empowermentSubmissions AS A
JOIN empTable AS B
ON B.[qid] = A.[nomineeQID]
WHERE A.[statusID] = 3
AND A.[locationID] = @locale
GROUP BY B.[Department]
ORDER BY totalNominations DESC
FOR XML PATH ('data'), TYPE, ELEMENTS, ROOT ('root');
END
这个问题是,JOIN仅由nomineeQID
加入,而不是subQID
加入。
我正在寻找的最终结果是:
部门客户服务部门提交了25份提名和90份提名
按两个计数的总和排序......
我试图在JOIN
再次subQID
,但被告知我不能两次加入同一张桌子。
有没有更简单的方法来实现这一目标?
答案 0 :(得分:0)
这是一种情况,您需要相互独立地收集您的计数。当两个连接条件都满足时,使用两个左连接将导致第一个左连接中的某些行计数两次。您可以使用相关子查询或外部应用来收集您的方案,以收集不同条件的计数。我这里没有提供COUNT(CASE ... )
选项,因为您在数据中没有任何一个或多个场景,您有两个外键到employees表。因此,设置样本数据:
declare @empowermentSubmissions table (submissionID int primary key identity(1,1), submissionDate datetime, nomineeQID INT, submitterQID INT, statusID INT, locationID INT)
declare @empTable table (QID int primary key identity(1,1), AreaDesc varchar(10), DepartmentDesc varchar(20))
declare @locale INT = 0
declare @n int = 1
while @n < 50
begin
insert into @empTable (AreaDesc, DepartmentDesc) values ('Area ' + cast((@n % 2)+1 as varchar(1)), 'Department ' + cast((@n % 4)+1 as varchar(1)))
set @n = @n + 1
end
set @n = 1
while @n < 500
begin
insert into @empowermentSubmissions (submissionDate, nomineeQID, submitterQID, StatusID, locationID) values (dateadd(dd,-(cast(rand()*600 as int)),getdate()), (select top 1 QID from @empTable order by newid()), (select top 1 QID from @empTable order by newid()), 3 + (@n % 2) - (@n % 3), (@n % 2) )
set @n = @n + 1
end
现在是OUTER APPLY
选项:
SELECT TOP 50 E.DepartmentDesc, SUM(N.Nominations) Nominations, SUM(S.TotalSubmissions) TotalSubmissions
FROM @empTable E
OUTER APPLY (
SELECT COUNT(submissionID) Nominations
FROM @empowermentSubmissions A
WHERE A.statusID = 3
AND A.nomineeQID = E.QID
AND A.locationID = @locale
) N
OUTER APPLY (
SELECT COUNT(submissionID) TotalSubmissions
FROM @empowermentSubmissions A
WHERE A.statusID = 3
AND A.submitterQID = E.QID
AND A.locationID = @locale
) S
GROUP BY E.DepartmentDesc
ORDER BY SUM(Nominations) + SUM(TotalSubmissions) DESC