Quantcast
Channel: Teradata Forums - Database
Viewing all articles
Browse latest Browse all 14773

Patient Census by hour of day - response (1) by dnoeth

$
0
0

 
Your narration sounds familiar, it's a variation of a generic problem, a count over a time series :-)
To solve it, you have to elaborate on details and expected result set.
 
One row for each point in time when the number of patients changes?
That's easy, the query looks basically like this:

SELECT
  ts,
  SUM(CASE WHEN typ IN ('Admitted', 'Transfer IN') THEN 1 ELSE -1 END) 
  OVER (ORDER BY ts ROWS UNBOUNDED PRECEDING) AS cnt
FROM tab

 
Then you have to decide what to do when there are multiple INs and OUTs at the same point in time.
Still one row per input row or aggregated?

SELECT
  ts,
  SUM(cnt) 
  OVER (ORDER BY ts ROWS UNBOUNDED PRECEDING) AS cnt
FROM
 (
   SELECT ts, SUM(CASE WHEN typ IN ('Admitted', 'Transfer IN') THEN 1 ELSE -1 END) AS cnt
   FROM tab
   GROUP BY 1
   HAVING cnt <> 0 
 ) dt

This returns no row when the the number of INs equals the number of OUTs, if you need it comment out the "HAVING cnt <> 0".
 
But based on your narrative you probably want one row per hour:

SELECT
  ts - (EXTRACT(MINUTE FROM ts) * INTERVAL '1' MINUTE) - (EXTRACT(SECOND FROM ts) * INTERVAL '1' SECOND) AS day_to_hour, 
  MAX(cnt)
FROM
 (
   SELECT
     ts,
     SUM(cnt) 
     OVER (ORDER BY ts ROWS UNBOUNDED PRECEDING) AS cnt
   FROM
    (
      SELECT ts, SUM(CASE WHEN typ IN ('Admitted', 'Transfer IN') THEN 1 ELSE -1 END) AS cnt
      FROM tab
      GROUP BY 1
      HAVING cnt <> 0
    ) dt
 ) AS dt
GROUP BY 1
ORDER BY 1

 
 
What if there were no INs/OUTs for several hours, do you still need one row per hour?

Then it's more complicated and it would help when you mention your TD release :-)

 

 

 

Dieter
 


Viewing all articles
Browse latest Browse all 14773

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>