Skip to content

Commit 47e3659

Browse files
committed
refactor _co.sql
1 parent a6c8e34 commit 47e3659

File tree

1 file changed

+20
-53
lines changed

1 file changed

+20
-53
lines changed

products/developments/sql/_co.sql

Lines changed: 20 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -28,62 +28,29 @@ IN PREVIOUS VERSION:
2828
co_.sql
2929
*/
3030
DROP TABLE IF EXISTS co_devdb;
31-
WITH
32-
order_certtype AS (
33-
SELECT
34-
*,
35-
CASE
36-
WHEN certificatetype = 'T- TCO' THEN 2
37-
WHEN certificatetype = 'C- CO' THEN 1
38-
END AS certorder
31+
CREATE TABLE co_devdb AS
32+
WITH latest AS (
33+
SELECT DISTINCT ON (jobnum)
34+
jobnum,
35+
numofdwellingunits::numeric AS co_latest_units,
36+
effectivedate AS co_latest_effectivedate,
37+
certificatetype AS certtype
3938
FROM dob_cofos
40-
),
41-
order_co AS (
42-
SELECT
43-
jobnum AS job_number,
44-
effectivedate::date AS effectivedate,
45-
numofdwellingunits::numeric AS units,
46-
certificatetype AS certtype,
47-
row_number() OVER (
48-
PARTITION BY jobnum
49-
ORDER BY effectivedate::date DESC, certorder ASC
50-
) AS latest,
51-
row_number() OVER (
52-
PARTITION BY jobnum
53-
ORDER BY effectivedate::date ASC
54-
) AS earliest
55-
FROM order_certtype
56-
WHERE jobnum IN (
57-
SELECT DISTINCT job_number
58-
FROM init_devdb
59-
)
60-
),
61-
draft_co AS (
39+
WHERE jobnum IN (SELECT job_number FROM init_devdb)
40+
ORDER BY
41+
jobnum ASC, effectivedate::date DESC, certificatetype ASC
42+
), completed_date AS (
6243
SELECT
63-
a.*,
64-
b._date_complete
65-
FROM (
66-
SELECT
67-
job_number,
68-
effectivedate AS co_latest_effectivedate,
69-
units AS co_latest_units,
70-
certtype AS co_latest_certtype
71-
FROM order_co
72-
WHERE latest = 1
73-
) AS a
74-
LEFT JOIN (
75-
SELECT
76-
job_number,
77-
effectivedate AS _date_complete
78-
FROM order_co
79-
WHERE earliest = 1
80-
) AS b ON a.job_number = b.job_number
44+
jobnum,
45+
min(effectivedate::date) AS _date_complete
46+
FROM dob_cofos
47+
GROUP BY jobnum
8148
)
8249
SELECT
83-
job_number,
50+
latest.jobnum AS job_number,
8451
_date_complete,
85-
co_latest_effectivedate,
52+
co_latest_effectivedate::date,
8653
co_latest_units,
87-
co_latest_certtype
88-
INTO co_devdb
89-
FROM draft_co;
54+
certtype
55+
FROM latest
56+
INNER JOIN completed_date ON latest.jobnum = completed_date.jobnum;

0 commit comments

Comments
 (0)