查询以查找确切计数

时间:2014-05-20 06:17:11

标签: sql sql-server sql-server-2008

下面是我需要查找确切计数的数据库表

[Request]

[RequestID] RequestName   RequestedOn
  1         XYZ            4/5/2014
  2         ABC            5/5/2014
  3         MNO            4/5/2014

[Inspection]

 InspectionID, [RequestID]
    1               1
    2               2
    3               3

[InspectionTrack]表

TrackID InspectionID StatusCode FinishedOn
1          1          0         5/5/2014
2          1          2         6/5/2014
3          1          5        6/5/2014
4          2          0        5/5/2014
5          2          2        7/5/2014
6          2          5        7/5/2014
7          3          0        20/5/2014

我需要完成请求的查询< = 15 Days& > 15天,其中Status 5是完成状态,这是我的查询,但是它返回错误的结果(即计数不应该越过3,在我的情况下它给出双/错)

SELECT 
    CASE
        WHEN DATEDIFF(DAY, RequestedOn, 
            CASE 
            WHEN IT.[StatusCode]=5 
            THEN FinishedOn 
            ELSE GETDATE() 
            END
        ) <= 15 
    THEN COUNT(DISTINCT R.[RequestID]) 
    ELSE 0 
    END AS Passed, 
    CASE 
        WHEN DATEDIFF(DAY, RequestedOn, 
            CASE 
            WHEN IT.[StatusCode]=5 
            THEN FinishedOn 
            ELSE GETDATE() 
            END
        ) > 15 
    THEN COUNT(DISTINCT R.[RequestID]) 
    ELSE 0 
    END AS Failed 
FROM 
    [Request] as R 
    INNER JOIN [Inspection] AS I 
        on  R.[RequestID]=I.[RequestID]
    INNER JOIN [InspectionTrack] AS IT 
        ON I.[InspectionID]=IT.[InspectionID]
GROUP BY 
    RequestedOn, 
    IT.[StatusCode], 
    FinishedOn

请帮忙

2 个答案:

答案 0 :(得分:1)

试试这个:

select sum(case when datediff(d,requestedon, finishedon) <= 15 then 1 else 0 end) 'Passed',
sum(case when datediff(d,requestedon, finishedon) > 15 or finishedon is null then 1 else 0 end) 'Failed'
from track t
right join inspection i on t.inspectionid = i.inspectionid
inner join request r on i.requestid = r.requestid
where isnull(t.statuscode,5) = 5

假设:如果track表中没有特定请求的记录,则应将其视为失败。

答案 1 :(得分:1)

尝试:

;WITH Results (PassFail) AS (
    SELECT CASE WHEN T.FinishedOn IS NULL THEN 0 WHEN DATEDIFF(DAY, R.RequestedOn, T.FinishedOn) > 15 THEN 0 ELSE 1 END AS PASSFAIL
    FROM Request R
    LEFT JOIN Inspection I ON R.RequestID = I.RequestID
    LEFT JOIN InspectionTrack T ON I.InspectionID = T.InspectionID AND T.StatusCode = 5
)
SELECT (SELECT COUNT(*) FROM Results WHERE PassFail = 1) AS Passed, (SELECT COUNT(*) FROM Results WHERE PassFail = 0) AS Failed