Skip to content
Advertisement

Having problem with Select using month/hour

The database is from a Hospital and the problem is when the month changes, like this: The patient gets to the UTI on the date 30/03/2020 6AM and left on 02/04/2020 11AM so theoretically they spend (18+24+24+11) 89 hours in total butIput this on Business Intelligence(BI) the BI thinks that they spent 77hours on the UTI only on March and didn’t show anything for April

So i have to divide like 30/03/2020 6AM end on 31/03/2020 23:59PM = 42h, and 01/04/2020 start on 00AM and end on 02/04/2020 11PM = 47h

So they achieve 77 hours but it is divided between March and April.

My goal is to divide this in SQL Server with select or something, i was reading about DATEPART/DATENAME but unsuccessfully.

The output expected in SQL

Output of this code on my database

Advertisement

Answer

What you need to do is add a row for each month into your data. One method is using an rCTe, however, I prefer to use a Tally as they are significantly faster for larger data sets; though here there’s likely to be little to no performance difference.

I assume 36 rows, 3 years, is enough here. I then use a small inline tally to create a row for each month for the start and end dates, and then a get the difference, in hours, for each month using DATEDIFF:

db<>fiddle

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement