2

我有一个问题跟踪数据库。我需要能够提供一个日期范围内每天打开和关闭的所有问题的报告。

我已经能够一次生成一列的结果......全部打开或全部关闭。我真的很想一次性完成所有工作,而不是在一份报告中分两部分提供结果。

有问题的列是 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
4

1 回答 1

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
于 2013-01-23T21:52:33.693 回答