Im trying to establish for any given datetime a tag that is purely dependent on the time part. However because the time part is cyclic I cant make it work with simple greater lower than conditions. I tried a lot of casting and shift one time to 24hour mark to kinda break the cycle However it just gets more and more complicated and still doesnt work.
Im using SQL-Server, here is the situation:
DECLARE @tagtable TABLE (tag varchar(10),[start] time,[end] time);
DECLARE @datetimestable TABLE ([timestamp] datetime)
Insert Into @tagtable (tag, [start], [end])
values ('tag1','04:00:00.0000000','11:59:59.9999999'),
('tag2','12:00:00.0000000','19:59:59.9999999'),
('tag3','20:00:00.0000000','03:59:59.9999999');
Insert Into @datetimestable ([timestamp])
values ('2022-07-24T23:05:23.120'),
('2022-07-27T13:24:40.650'),
('2022-07-26T09:00:00.000');
tagtable:
| tag | start | end |
|---|---|---|
| tag1 | 04:00:00.0000000 | 11:59:59.9999999 |
| tag2 | 12:00:00.0000000 | 19:59:59.9999999 |
| tag3 | 20:00:00.0000000 | 03:59:59.9999999 |
for given datetimes e.g. 2022-07-24 23:05:23.120, 2022-07-27 13:24:40.650, 2022-07-26 09:00:00.000
the desired result would be:
| date | tag |
|---|---|
| 2022-07-25 | tag3 |
| 2022-07-27 | tag2 |
| 2022-07-26 | tag1 |
As I wrote i tried to twist this with casts and adding and datediffs
SELECT
If(Datepart(Hour, a.[datetime]) > 19,
Cast(Dateadd(Day,1,a.[datetime]) as Date),
Cast(a.[datetime] as Date)
) as [date],
b.[tag]
FROM @datetimestable a
INNER JOIN @tagtable b
ON SomethingWith(a.[datetime])
between SomethingWith(b.[start]) and SomethingWith(b.[end])