1

I need to perform two different counts in one single query.

First Query: count number of transactions from today 30 days back.
Second Query: count number of transactions from last 60 until last 30 days.

I have first query working fine as:

SELECT 
  COUNT(*) AS sales 
FROM
  transactions 
WHERE DATE(created) > DATE_SUB(NOW(), INTERVAL 30 DAY) 
  AND STATUS = 1;

How can I incorporate the second query into the above?

1 Answer 1

3

You can use COUNT and CASE WHEN:

SELECT 
  COUNT(CASE WHEN DATE(created) > DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) AS c1,
  COUNT(CASE WHEN DATE(created) <= DATE_SUB(NOW(), INTERVAL 30 DAY) THEN 1 END) AS c2
FROM transactions 
WHERE DATE(created) > DATE_SUB(NOW(), INTERVAL 60 DAY) 
  AND STATUS = 1;

or UNION:

SELECT COUNT(*) AS sales 
FROM transactions 
WHERE DATE(created) > DATE_SUB(NOW(), INTERVAL 30 DAY) 
  AND STATUS = 1
UNION ALL
SELECT COUNT(*) 
FROM transactions 
WHERE DATE(created) > DATE_SUB(NOW(), INTERVAL 60 DAY) 
  AND DATE(created) < DATE_SUB(NOW(), INTERVAL 30 DAY) 
  AND STATUS = 1
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you that works perfect. I have not tested Union, but using case is lot cleaner.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.