时间范围

时间:2018-02-15 17:52:13

标签: sql-server tsql

我需要在一个重叠天数的时间范围内每天返回结果计数。

所以从晚上8点到早上8点,从M-F开始的每一天都会返回该时间段的计数。并且整年都这样做。

这就是我所拥有的,而且我可以做一个简单的介绍,如果我只是想在一天,但我不知道如何迭代几天,特别是当开始是在一天而结束在下一天但跳过那些在周六或周日开始的人。

SELECT TOP (50)
    ClientVisit.visittype,
    ClientVisit.location_id,
    ClientVisit.visittype_id,
    Location.location_desc,
    Location.location_code,
    ClientVisit.timein,
    ClientVisit.timeout,
    ClientVisit.visit_dateday
FROM 
    ClientVisit
INNER JOIN 
    Location ON ClientVisit.location_id = Location.location_id
WHERE
    (ClientVisit.visittype Like '%Open Chart%'
     OR ClientVisit.visittype LIKE '%Diag%')
    AND (Location.location_code = 'Access-505'
         OR Location.location_code = 'Access-hosp')
    AND (ClientVisit.timein BETWEEN @param1 AND @param2)

1 个答案:

答案 0 :(得分:1)

过滤一周中的几天和一天中的几个小时很容易。这个group by是否会得到你想要完成的计数?

SELECT CAST(ClientVisit.timein AS DATE) AS DT, COUNT(*)
FROM ClientVisit INNER JOIN Location
    ON ClientVisit.location_id = Location.location_id
WHERE
        (ClientVisit.visittype Like '%Open Chart%' OR ClientVisit.visittype LIKE '%Diag%')
    AND (Location.location_code = 'Access-505' OR Location.location_code = 'Access-hosp')
    -- Use date params rather than datetime
    AND CAST(ClientVisit.timein AS DATE) BETWEEN @param1 AND @param2
    -- M-F assuming @@DATEFIRST is Sunday (7)
    AND DATEPART(weekday, ClientVisit.timein) BETWEEN 2 AND 6
    -- time of day. won't include the instant of 8:00:00am
    AND (   DATEPART(hour, ClientVisit.timein) BETWEEN 8 AND 23
        OR  DATEPART(hour, ClientVisit.timein) BETWEEN 0 AND 7)
GROUP BY CAST(ClientVisit.timein AS DATE);

如果您需要将时间从晚上8点到早上8点作为一个班次处理,那么您可以在之前调整时间,以便午夜之后的时间被视为前一天的一部分:

WITH AdjustedVisit AS (
    SELECT *, DATEADD(hour, -8, timein) AS adjustedin FROM ClientVisit)
    -- Use date params rather than datetime
    WHERE CAST(timein AS DATE) BETWEEN @param1 AND @param2
)
SELECT CAST(v.adjustedin AS DATE) AS DT, COUNT(*)
FROM AdjustedVisit AS v INNER JOIN Location AS l
    ON v.location_id = l.location_id
WHERE
        (v.visittype Like '%Open Chart%' OR v.visittype LIKE '%Diag%')
    AND (l.location_code = 'Access-505' OR l.location_code = 'Access-hosp')
    -- M-F assuming @@DATEFIRST is Sunday (7)
    AND DATEPART(weekday, v.adjustedin) BETWEEN 2 AND 6
    -- time of day. won't include the instant of 8:00:00am
    AND DATEPART(hour, v.adjustedin) BETWEEN 12 AND 23
GROUP BY CAST(v.adjustedin AS DATE);