View difference between Paste ID: K2WDtbDx and Q5nrEx9A
SHOW: | | - or go back to the newest paste.
1-
-- https://pgexercises.com/questions/date/daysinmonth.html
1+
-- https://pgexercises.com/questions/date/utilisationpermonth.html
2-
-- date_part does not work for the second column of the second clause, but date_trunc does
2+
-- longer than the recommended solution, but more transparent IMO
3
4-
with gs as (select generate_series(
4+
-- count available slots per month
5-
	  '2012-01-01'::timestamp,
5+
with t1 as (
6-
	  '2012-12-31'::timestamp,
6+
	select 
7-
	  '1 month'::interval) as month)
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-
select date_part('month', month) as m,
9+
		from cd.bookings
10-
		(date_trunc('month', month)+'1 month'::INTERVAL)-date_trunc('month', month) as len
10+
		group by 1, 2),
11-
from gs
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