Skip to content

Instantly share code, notes, and snippets.

@shreyas-satish
Last active January 20, 2016 13:14
Show Gist options
  • Save shreyas-satish/d721a3dbaafb4398163e to your computer and use it in GitHub Desktop.
Save shreyas-satish/d721a3dbaafb4398163e to your computer and use it in GitHub Desktop.
Subquery using WITH
WITH cohort as (
select author_id from articles where datetime >= '2015-01-01' and datetime <= '2015-01-31'
), return_rate as (
select date_trunc('month', datetime) AS month, count(*) FROM articles WHERE author_id IN (SELECT author_id FROM cohort) AND datetime >= '2015-02-01' GROUP BY month ORDER BY count ASC
)
SELECT to_char(month, 'Mon YYYY'), count from return_rate;
CREATE TABLE articles (
id integer CONSTRAINT firstkey PRIMARY KEY,
author_id integer NOT NULL,
datetime timestamp without time zone
);
INSERT INTO articles VALUES (1, 1, '2015-01-01');
INSERT INTO articles VALUES (2, 1, '2015-02-01');
INSERT INTO articles VALUES (3, 1, '2015-03-01');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment