NonplayerCharacter

PGexercises.com | Monthly facility utilisation rate

Mar 22nd, 2022 (edited)
220
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -- https://pgexercises.com/questions/date/utilisationpermonth.html
  2. -- longer than the recommended solution, but more transparent IMO
  3.  
  4. -- count available slots per month
  5. with t1 as (
  6.     select
  7.         date_trunc('month',starttime) as month,
  8.         25*LEFT(((DATE_TRUNC('month', starttime)+'1 month'::INTERVAL)-DATE_TRUNC('month', starttime))::TEXT,2)::INTEGER AS len_int
  9.         from cd.bookings
  10.         group by 1, 2),
  11.  
  12. -- count used slots per month per facility
  13. t2 as(
  14.     select f.name,
  15.         date_trunc('month',starttime) as month,
  16.         sum(slots) as used_slots
  17.         from cd.bookings b
  18.         join cd.facilities f
  19.         on f.facid = b.facid
  20.         group by 1, 2
  21.         order by 1 asc, 2 asc
  22. ),
  23.  
  24. -- line up facility, month, available slots, used slots
  25. t3 as (
  26.     select  name,
  27.             t.month,
  28.             len_int,
  29.             sum(used_slots) as usedslots
  30.     from t1 t
  31.     join t2 d
  32.     on t.month = d.month
  33.     group by 1, 2, 3
  34.     order by name asc
  35. )
  36. -- finally divide one by the other
  37. select name, month, ROUND(100*(usedslots/len_int),1) as uti
  38. from t3
Add Comment
Please, Sign In to add comment