-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb_comparison_queries.sql
59 lines (56 loc) · 2.2 KB
/
db_comparison_queries.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
-- This query returns week over week eviction filings
-- in wide format (with districts in columns).
-- This outer query is the long-to-wide pivot.
SELECT
week_start,
week_end,
COALESCE(max(n) FILTER (WHERE district = 'central'), 0) AS C_db,
COALESCE(max(n) FILTER (WHERE district = 'eastern'), 0) AS E_db,
COALESCE(max(n) FILTER (WHERE district = 'metrosouth'), 0) AS MS_db,
COALESCE(max(n) FILTER (WHERE district = 'northeast'), 0) AS NE_db,
COALESCE(max(n) FILTER (WHERE district = 'southeast'), 0) AS SE_db,
COALESCE(max(n) FILTER (WHERE district = 'western'), 0) AS W_db
FROM (
-- This inner query groups filings by week.
SELECT
-- MassLandlords week starts on Sunday, not Monday.
-- Thus, the INVERVAL shift.
date_trunc('week', file_date + INTERVAL '1 day') - INTERVAL '1 day' AS week_start,
date_trunc('week', file_date + INTERVAL '1 day') + INTERVAL '5 day' AS week_end,
district,
COUNT(*) AS n
FROM filings
GROUP BY week_start, week_end, district
ORDER BY week_start
) AS long
GROUP BY week_start, week_end
ORDER BY week_start, week_end;
-- This query returns week over week eviction filings
-- ~~where we successfully pulled the address~~
-- in wide format (with districts in columns).
-- This outer query is the long-to-wide pivot.
SELECT
week_start,
week_end,
COALESCE(max(n) FILTER (WHERE district = 'central'), 0) AS C_db_add,
COALESCE(max(n) FILTER (WHERE district = 'eastern'), 0) AS E_db_add,
COALESCE(max(n) FILTER (WHERE district = 'metrosouth'), 0) AS MS_db_add,
COALESCE(max(n) FILTER (WHERE district = 'northeast'), 0) AS NE_db_add,
COALESCE(max(n) FILTER (WHERE district = 'southeast'), 0) AS SE_db_add,
COALESCE(max(n) FILTER (WHERE district = 'western'), 0) AS W_db_add
FROM (
-- This inner query groups filings by week.
SELECT
-- MassLandlords week starts on Sunday, not Monday.
-- Thus, the INVERVAL shift.
date_trunc('week', file_date + INTERVAL '1 day') - INTERVAL '1 day' AS week_start,
date_trunc('week', file_date + INTERVAL '1 day') + INTERVAL '5 day' AS week_end,
district,
COUNT(*) AS n
FROM filings
WHERE add_p IS NOT NULL
GROUP BY week_start, week_end, district
ORDER BY week_start
) AS long
GROUP BY week_start, week_end
ORDER BY week_start, week_end;