我有跟踪数据库的问题。我需要能够在日期范围内提供每天打开和关闭的所有问题的报告。
我已经能够一次生成一列的结果......全部打开或全部关闭。 我真的很想一次性完成所有这一切,而不是必须在两个部分提供结果时才真正报告。
有问题的列是dteOpen(datetime),dteClosed(datetime)。
Declare @dt1 datetime = '1/1/1900',
Declare @dt2 datetime = '1/1/1900',
Declare @tT int = 0IF OBJECT_ID('tempdb..#TempDate') IS NoT NULL
DROP TABLE #TempDate
;WITH ctedaterange
AS (SELECT [rn]=Row_number()
OVER(
ORDER BY (SELECT NULL))
FROM sys.objects a
CROSS JOIN sys.objects b
CROSS JOIN sys.objects c
CROSS JOIN sys.objects d)
SELECT CAST(Dateadd(dd, rn, @dt1) AS DATE) As DateRange
into #TempDate
FROM ctedaterange
WHERE [rn] <= Datediff(dd, @dt1, @dt2)
Select td.DateRange,Count(ID)as countNumber
from #TempDate td
LEFT outer JOIN tblProblemslist pl
ON CAST(pl.dtmOpen AS DATE) = td.DateRange
AND dtmOpen between @dt1 and @dt2
AND ticketType = @tT
Group by td.DateRange
Order by td.DateRange
答案 0 :(得分:0)
基本上,只需再次加入tblProblemsList
,但要考虑已结束问题的条件。然后,您可以在查询中添加另一个COUNT
。
在不了解您的表格结构的情况下,我猜你想要这样的东西:
DECLARE @from datetime = '12/1/2012';
DECLARE @through datetime = '12/31/2012';
DECLARE @then datetime = DATEADD(dd, -1, @from);
Declare @ticketType int = 0;
DECLARE @dateRange table
(
dateRange date
, id int IDENTITY
)
-- use a loop to populate the @daterange table var
-- rather than selecting from sys.object and
-- using a ranking function
WHILE @then < @through
BEGIN
INSERT INTO @dateRange (dateRange) VALUES (DATEADD(dd, 1, @then))
SET @then = DATEADD(dd, 1, @then)
END
SELECT dateRange.dateRange
, COUNT(listOfOpened.id) AS countOfOpened
, COUNT(listOfClosed.id) AS countOfClosed
FROM @dateRange AS dateRange
LEFT OUTER JOIN tblProblemsList AS listOfOpened
ON CAST(listOfOpened.dtmOpen AS DATE) = dateRange.dateRange
AND listOfOpened.dtmOpen BETWEEN @from AND @through
AND listOfOpened.ticketType = @ticketType
LEFT OUTER JOIN tblProblemsList AS listOfClosed
ON CAST(listOfClosed.dtmClosed AS DATE) = dateRange.dateRange
AND listOfClosed.dtmClosed BETWEEN @from AND @through
AND listOfClosed.ticketType = @ticketType
GROUP BY dateRange.dateRange
ORDER BY dateRange.dateRange