Prattski
Prattski

Reputation: 2060

2 different queries on same table with count and group by

I have a table entries with the following columns: id, email, sku, payment, created_at

I need to write a few queries to get some analytics on the entries. The two queries I'd like to combine into one are:

SELECT sku, count(email) AS total_current FROM entries WHERE payment IS NOT NULL AND created_at >= DATE_SUB(NOW(), INTERVAL 1 WEEK) GROUP BY sku ORDER BY sku ASC

And

SELECT sku, count(email) AS total_previous FROM entries WHERE payment IS NOT NULL AND created_at < DATE_SUB(NOW(), INTERVAL 1 WEEK) AND created_at >= DATE_SUB(NOW(), INTERVAL 2 WEEK) GROUP BY sku ORDER BY sku ASC

The goal here is to have 1 set of results with 3 columns that show the number of records for each sku for one date range in the 2nd column, and the number of records for the same sku in the 3rd column.

  1. Sku (where everything is grouped)

  2. total_current (count # of records that fall within the first query's date range for each separate sku)

  3. total_previous (count # of records that fall within the second query's date range for each separate sku)

And the results should be sorted by sku ascending.

I have tried a lot of different things using UNION, and JOIN, etc., but with no luck so far.

Upvotes: 2

Views: 1372

Answers (1)

Giorgos Betsos
Giorgos Betsos

Reputation: 72165

You can use conditional aggregation to combine the two queries:

SELECT sku, 
       count(CASE 
                WHEN created_at >= DATE_SUB(NOW(), INTERVAL 1 WEEK)  THEN email
             END) AS total_current,
       count(CASE 
                WHEN  created_at < DATE_SUB(NOW(), INTERVAL 1 WEEK) AND
                     created_at >= DATE_SUB(NOW(), INTERVAL 2 WEEK)  THEN email
             END) AS total_previous
FROM entries 
WHERE payment IS NOT NULL AND 
      created_at >= DATE_SUB(NOW(), INTERVAL 2 WEEK)
GROUP BY sku 
ORDER BY sku ASC

Upvotes: 2

Related Questions