I'm using PostgreSQL 9.3.9 to run two different queries that give different results but both group by "month-year". I was wondering how I would create a query to give me the same data in one table?
Query 1:
SELECT CONCAT(EXTRACT(MONTH FROM startedPayingDate), '-',
EXTRACT(YEAR FROM startedPayingDate)) AS "Month",
COUNT(*) AS "Total AB Paying Customers"
FROM (
SELECT cm.customer_id, MIN(cm.created_at) AS startedPayingDate
FROM customerusermap AS cm, users as u
WHERE cm.customer_id = u.customer_id AND cm.user_id<>u.id
GROUP BY cm.customer_id ) AS t
GROUP BY 1, EXTRACT(MONTH FROM startedPayingDate), EXTRACT(YEAR FROM startedPayingDate)
ORDER BY EXTRACT(YEAR FROM startedPayingDate), EXTRACT(MONTH FROM startedPayingDate);
Results in something like this:
Month | Total AB Paying Customers
---------------------------------
3-2014 | 2
4-2014 | 4
Query 2:
SELECT concat(extract(MONTH from u.created_at),'-',extract(year from u.created_at)) as "Month",
count(u.email) as "Total SMB Paying Customers"
FROM customerusermap AS cm, users AS u
WHERE cm.customer_id = u.customer_id AND cm.user_id = u.id AND u.paid_status = 'paying'
GROUP by 1,extract(month from u.created_at),extract(year from u.created_at)
order by extract(year from u.created_at),extract(month from u.created_at);
Results in something like this:
Month | Total SMB Paying Customers
-----------------------------------
2-2014 | 3
3-2014 | 8
4-2014 | 5
Desired result
I want to merge these two queries into something that results as shown and also orders by year and month (i.e. oldest to newest):
Month | Total AB Paying Customers | Total SMB Paying Customers | Total | Cumulative
-------------------------------------------------------------------------------------
2-2014 | 0 | 3 | 3 | 3
3-2014 | 2 | 8 | 10 | 13
4-2014 | 4 | 5 | 9 | 22
Table definitions
CREATE TABLE users (
id serial NOT NULL,
firstname character varying(255) NOT NULL,
lastname character varying(255) NOT NULL,
email character varying(255) NOT NULL,
created_at timestamp without time zone NOT NULL DEFAULT now(),
customer_id character varying(255) DEFAULT NULL::character varying,
companyname character varying(255),
primary_user_id integer,
paid_status character varying(255), -- updated from comment
CONSTRAINT users_pkey PRIMARY KEY (id),
CONSTRAINT primary_user_id_fk FOREIGN KEY (primary_user_id) REFERENCES users (id),
CONSTRAINT users_uuid_key UNIQUE (uuid)
)
Whereas the customerusermap table looks like:
CREATE TABLE customerusermap (
id serial NOT NULL,
user_id integer NOT NULL,
customer_id character varying(255) NOT NULL,
created_at timestamp without time zone NOT NULL DEFAULT now(),
CONSTRAINT customerusermap_pkey PRIMARY KEY (id),
CONSTRAINT customerusermap_user_id_fkey FOREIGN KEY (user_id) REFERENCES users (id),
CONSTRAINT customerusermap_user_id_key UNIQUE (user_id)
);