SQL Server SQL Query looking at time slots within the past 24hrs

5uzkadbs  于 2023-03-28  发布在  其他
关注(0)|答案(1)|浏览(124)

I am looking to write a query specifying a time of 7am-3pm, 3pm-11pm, and 11pm-7am which "only" looks at the prior 24 hours. I currently have a query which looks at the previous 24 hour but I want the previous 24 hour broken out by the above time slots. Any help would be appreciated.

This is the current query which just takes into account the previous day....

SELECT "inmain"."calltime", "inmain"."business", "inmain"."agency", "inmain"."case_id", "inmain"."nature", "inmain"."street", "inmain"."inci_id"
FROM   "cad"."dbo"."inmain" "inmain"
WHERE  "inmain"."agency" = 'YUPD' 
AND "inmain"."calltime" > getdate()-1
ORDER BY "inmain"."nature"
tmb3ates

tmb3ates1#

You could create a scalar-valued function that changes a datetime to an ID. There are a lot of ways to implement this. Here's one that turns a date into YYYYMMDDS, where S is the time slot (1 (7a to 3p) through 3 (11p to 7a)).

So, for example, 3/24/2023 6:00p would become 202303242.

Here's the function...

create function udfGetTimeSlotId 
(
    @dt as datetime2
)
returns varchar(9)
as
begin
    
    declare @slot as varchar(9)

    -- Add the T-SQL statements to compute the return value here
    set @slot = 
    case 
        when datepart(hour,@dt) >= 7 and datepart(hour,@dt) < 15 then format(@dt,'yyyyMMdd') + '1'
        when datepart(hour,@dt) >= 15 and datepart(hour,@dt) < 23 then format(@dt,'yyyyMMdd') + '2'
        when datepart(hour,@dt) >= 23 then format(@dt,'yyyyMMdd') + '3'
        when datepart(hour,@dt) < 7 then format(dateadd(d,-1,@dt),'yyyyMMdd') + '3'  --nightime shift, need to go back one day
    end
    return @slot

end
go

And here's how you use it...

select dbo.udfGetTimeSlotId('3/24/2023 6:00')  --202303233 (note that the date code is one day earlier)
select dbo.udfGetTimeSlotId('3/24/2023 12:00')  --202303241
select dbo.udfGetTimeSlotId('3/24/2023 23:00')  --202303243

You could then use that ID to compare to earlier IDs, etc. Or tweak the whole thing so that it returns the date and slot separately, being careful to drop back one day for shifts that start between Midnight and 7a.

For your specific requirement, you would change the where clause:

SELECT "inmain"."calltime", "inmain"."business", "inmain"."agency", "inmain"."case_id", "inmain"."nature", "inmain"."street", "inmain"."inci_id"
FROM   "cad"."dbo"."inmain" "inmain"
WHERE  "inmain"."agency" = 'YUPD' 
AND dbo.udfGetTimeSlotId("inmain"."calltime") = dbo.udfGetTimeSlotId(getdate()-1) 
ORDER BY "inmain"."nature"

相关问题