0

I have to make an query on a table where the datetime field is of type datetimeoffset. The query itself is already difficult, but now working with conversions makes it even more complicated. What I want out of the table is to retrieve everything between 23:00 previous day to 07:00 the next morning for the past 2 weeks. I have tried numerous ways, but think I am just staring at a screen momentarily. Below is one of my last attempts before posting here, what am I missing here:

SELECT * 
FROM Occurrences 
 WHERE SWITCHOFFSET(CreatedOn,'+01:00') >= DATEADD(hh,23,DATEADD(day, DATEDIFF(day, 0, 
  SWITCHOFFSET(CreatedOn,'+01:00') - 1), 0))
 AND SWITCHOFFSET(CreatedOn,'+01:00') <    DATEADD(hh,7,DATEADD(day, DATEDIFF(day, 0, 
  SWITCHOFFSET(CreatedOn,'+01:00')), 0))
 ORDER BY CreatedOn DESC 

Just note This is without the 2 weeks filter. Just wanted to see some results atleast, but get an error:

Operand type clash: datetimeoffset is incompatible with int

The CreatedOn has a entry like "2022-11-15 09:24:13.6096718 +01:00" and the type of field is a datetimeoffset(7)

This does work though in it simplest form:

  SELECT TOP 1 SWITCHOFFSET(CreatedOn,'+01:00') FROM Occurrences ORDER BY CreatedOn DESC
3
  • Which DBMS are you using? Microsoft SQL Server? Please add the appropriate tag for your DBMS. Commented Dec 13, 2022 at 12:51
  • SWITCHOFFSET(CreatedOn,'+00:01') seems wrong; that would be a 1 minute offset from UTC. Is that what you actually want? No one actually observes that. Commented Dec 13, 2022 at 13:47
  • Jeeze, how did I not see that. Thanks for your observation. But unfortunately that was not the bug........but another bug ;-) Will fix it in my original post Commented Dec 13, 2022 at 14:51

1 Answer 1

1

Just check that the hour part is either above 23 or below 7, then check it occurred less than 2 weeks ago.

SELECT *
FROM Occurrences
WHERE (DATEPART(hh, SWITCHOFFSET(CreatedOn,'+00:01')) >= 23 OR DATEPART(hh, SWITCHOFFSET(CreatedOn,'+00:01')) < 7) AND (SWITCHOFFSET(CreatedOn,'+00:01') > CONVERT(datetimeoffset, DATEADD(day, -14, GETDATE()),'+00:01'))
ORDER BY CreatedOn DESC
Sign up to request clarification or add additional context in comments.

1 Comment

Actually, rookie mistake I'va made. It makes sense to check if the hour part is either above 23 or below 7, the date is ordered...so it works :-) Your solution helped me except the 3rd parameter of the CONVERT I changed from '+00:01' to 103. It expects an int and not a varchar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.