是否可以将这两个查询合并为一个?现在,我运行了 2 个单独的查询,这些查询显示:
- 用户名以及他们打开了多少个问题
- 用户名以及他们关闭了多少个问题
开放式问题:
SELECT FirstName +' ' + LastName AS 'UserName', COUNT(u.UserID) AS IssuesOpened
FROM Users u
LEFT OUTER JOIN Issues i ON i.CreatedByUserID = u.UserID
WHERE i.DateCreated BETWEEN '06/30/2012 23:59:59' AND '07/01/2013 00:00:01'
GROUP BY LastName, FirstName
结果看起来像这样:
UserName | IssuesOpened
-----------------------
User 1 10
User 2 8
User 3 55
已关闭的问题:
SELECT FirstName +' ' + LastName AS 'UserName', COUNT(u.UserID) AS IssuesClosed
FROM Users u
LEFT OUTER JOIN Issues i ON i.ResolvedByUserID = u.UserID
WHERE ResolvedDate BETWEEN '06/30/2012 23:59:59' AND '07/01/2013 00:00:01'
GROUP BY LastName, FirstName
结果看起来像这样:
UserName | IssuesClosed
-----------------------
User 1 8
User 2 2
User 3 40
我想加入这两个查询来得到这个:
UserName | IssuesOpened | IssuesClosed
--------------------------------------
User 1 10 8
User 2 8 2
User 3 55 40
我尝试了一些丑陋的东西,像这样:
SELECT FirstName + ' ' + LastName AS UserName,
(SELECT COUNT(u.UserID)
FROM Users u
LEFT OUTER JOIN Issues i ON i.ResolvedByUserID = u.UserID
WHERE ResolvedDate BETWEEN '06/30/2012 23:59:59' AND '07/01/2013 00:00:01')
AS IssuesClosed,
(SELECT COUNT(u.UserID)
FROM Users u
LEFT OUTER JOIN Issues i ON i.CreatedByUserID = u.UserID
WHERE i.DateCreated BETWEEN '06/30/2012 23:59:59' AND '07/01/2013 00:00:01')
AS IssuesOpened
FROM Users u
GROUP BY FirstName, LastName
但是因为我删除了GROUP BY
每个子查询中的子句,它只返回总行数。
更新
由于我无法将数据加载到 SqlFiddle 中(查询窗口和模式窗口都只能容纳 8000 个字符),我想出了一些我的结果与 sgeddes 结果的屏幕截图:
sgeddes 结果
让我印象深刻的一件事是,如果您注意到 sgeddes 结果,最后一行,用户“Web***”有 449 个“已关闭”。这是不可能的,因为该用户 (Web***) 是我们如何确定客户如何通过我们的网站打开问题的占位符。该假用户无权访问我们的系统,也无法关闭任何工单。