1

我试图获取一个人的总记录时间超过一定数量的天数。现在我只能获得一列关于天数的准确数据(我目前在所有天数列中都超过 60 天。基本上我想为所有没有时间进行该特定记录的人返回 0长度增量。我还想获得所有增量的天数,这些人的天数以这些增量记录长度。

本质上,我希望我可以在定义列时将“Where”子句与列名放在一起。(我知道它不会那样工作)解决这个问题的最佳方法是什么?

这是我的代码:

WITH CTERecordingsByDate AS
(
    SELECT      Person.FirstName,
                Person.LastName,
                CAST(Created AS DATE) AS Whole_Date,
                SUM(Length)/60 AS Recordings_Sum, --Length is in seconds
    FROM        Recordings
    JOIN        Person ON Recordings.PersonID=Person.ID
    WHERE       Created BETWEEN '2013-07-01 00:00:00.000' 
                        AND     '2013-08-01 00:00:00.000'
    GROUP BY    Person.FirstName, 
                Person.LastName,
                CAST(Created AS DATE)
)

SELECT      FirstName, 
            LastName, 
            COUNT(*) AS DaysAbove60
            COUNT(*) AS DaysAbove100
            COUNT(*) AS DaysAbove140
FROM        CTERecordingsByDate
WHERE       Recordings_Sum >= 60
AND         Recordings_Sum < 100
GROUP BY    FirstName, LastName
ORDER BY    COUNT(*) DESC
4

1 回答 1

2

删除 WHERE 子句并在 COUNT 函数中使用 CASE:

COUNT(case when Recordings_Sum >= 60 AND Recordings_Sum < 100 then 1 end) AS DaysAbove60
COUNT(case when Recordings_Sum >= 100 AND Recordings_Sum < 140 then 1 end) AS DaysAbove100
COUNT(case when Recordings_Sum >= 140 then 1 end) AS DaysAbove140
于 2013-08-23T17:33:43.533 回答