In the following table (called status ) I need to display the city codes having the status '01' by the end of 2015. The status_date column stores the date the city changed its status.
gid | town | status | status_date -----+-----------+---------+------------- 1 | 86001 | 00 | 2000-01-01 2 | 86001 | 01 | 2016-03-01 3 | 86002 | 01 | 2000-01-01 4 | 86003 | 00 | 2000-01-01 5 | 86003 | 01 | 2015-03-01 6 | 86003 | 02 | 2015-09-01
I can achieve this with the following query, which is a bit long:
WITH tab AS (SELECT town, MAX(status_date) FROM status GROUP BY town) SELECT t.town FROM tab t LEFT JOIN status s ON t.town = s.town AND t.max = s.status_date WHERE t.max < '2016-01-01' AND s.status = '01' ;
Result:
town ------- 86002
Any idea on how to make this query easier? Is WITH essential?
To create a table for testing:
CREATE TABLE status (gid serial NOT NULL, town CHARACTER VARYING(5), status CHARACTER VARYING(2), status_date DATE) ; INSERT INTO status (town, status, status_date) VALUES ('86001', '00', '2000-01-01'), ('86001', '01', '2016-03-01'), ('86002', '01', '2000-01-01'), ('86003', '00', '2000-01-01'), ('86003', '01', '2015-03-01'), ('86003', '02', '2015-09-01') ;