我有一个SQL数据
BugID Request Date Closed Date
--------------------------------
1234 11/1/2013 11/5/2013
2345 11/1/2013 11/2/2013
2435 11/2/2013 11/2/2013
6345 11/3/2013 11/5/2013
9364 11/5/2013 11/6/2013
我希望结果是
Date Requested Bugs Closed Bugs Total Open Total Closed
----------------------------------------------------------------
11/1/2013 2 0 2 0
11/2/2013 1 2 3 2
11/3/2013 1 0 4 2
11/5/2013 1 1 5 3
11/6/2013 0 1 5 4
是否可以通过Transact SQL?
答案 0 :(得分:3)
这样的事情可以解决问题:
with allDates (date) as
(
select requestDate from dbo.bugs
union select closedDate from dbo.bugs
)
select date,
(select count(*) from dbo.bugs where requestDate = a.date) as bugsRequested,
(select count(*) from dbo.bugs where closedDate = a.date) as bugsClosed,
(select count(*) from dbo.bugs where a.date between requestDate and closedDate) AS bugsOpen,
(select count(*) from dbo.bugs where closedDate<=a.date) AS totalClosed
from allDates a
答案 1 :(得分:1)
你可以在你的SUM / COUNT函数中使用CASE语句
SELECT CAST([Request Date] AS DATE) AS [Request Date]
, COUNT(*) AS [Requested Bugs]
, COUNT(CASE WHEN [Closed Date] IS NOT NULL THEN 1 ELSE NULL END) AS [Closed Bugs]
, COUNT(CASE WHEN [Closed Date] IS NULL THEN 1 ELSE NULL END) AS [Total Open]
FROM Table_Name
GROUP BY CAST([Request Date] AS DATE)
我在这里考虑了一个Closed colum,它将指示哪些作业仍处于打开状态,它可能是一个字段或其他任何内容,但主要的想法是向您展示如何在聚合函数内使用CASE语句只计算某些行。