Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server query for calculating daily census

Tags:

sql-server

I'm having a problem with a query that populates the daily census(# of current inpatients) for a hospital unit. This previous post is where I found the query.

SELECT 
    [date], COUNT (DISTINCT                                                                           
                       CASE WHEN admit_date <= [date] AND discharge_date >= [date] THEN id END)) AS census
FROM 
    dbo.patients, dbo.census
GROUP BY 
    [date]
ORDER BY 
    [date] 

There are 2 tables:

  • dbo.patients with id, admit_date, and discharge_date columns
  • dbo.census has a date column with every date since 2017, and a census column, which is blank

The query populates the census column, but the census count diminishes toward the end of the dates to smaller numbers then it should. For example, there are 65 null values for discharge_date, so there should be a census count of 65 for today's date, but the query produces a count of 8.

like image 853
RickP Avatar asked Oct 29 '25 17:10

RickP


1 Answers

Probably need to account for NULL discharge date

SELECT [date], COUNT (DISTINCT                                                                           
CASE WHEN admit_date <= [date] AND COALESCE(discharge_date, GETDATE()) >= [date] THEN id END))
AS census

FROM dbo.patients
CROSS JOIN dbo.census

GROUP BY [date]
ORDER BY [date] 

That is, assuming [date] is some sort of current date/time stamp. Also, as per Sean Lange's comment, if you really want a CROSS JOIN then you should specify that in the query.

like image 126
BJones Avatar answered Oct 31 '25 07:10

BJones



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!