Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way of running same SELECT on multiple data in MySQL

I have pretty simple select, let's say:

SELECT COUNT(added) FROM users WHERE added < "2015-07-30"

Can I run this select in some simple way not only for the given date, but also for, let's say, 7 days, each row showing count up to that specific day?

EDIT: Here's my SQL building a table:

CREATE TABLE users (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
 added DATE
);

INSERT INTO users (added) VALUES ("2015-07-30");
INSERT INTO users (added) VALUES ("2015-07-29");
INSERT INTO users (added) VALUES ("2015-07-28");
INSERT INTO users (added) VALUES ("2015-07-21");
INSERT INTO users (added) VALUES ("2015-07-26");
INSERT INTO users (added) VALUES ("2015-07-25");
INSERT INTO users (added) VALUES ("2015-07-24");
INSERT INTO users (added) VALUES ("2015-07-23");
INSERT INTO users (added) VALUES ("2015-07-29");
INSERT INTO users (added) VALUES ("2015-07-22");
INSERT INTO users (added) VALUES ("2015-07-20");
INSERT INTO users (added) VALUES ("2014-02-10");

I expect result like that:

    DATE   | Count |
--------------------                   
2015-07-30 |  12   |
2015-07-29 |  11   |   
2015-07-28 |  10   |
2015-07-27 |   9   |
2015-07-26 |   9   |
2015-07-25 |   8   |
2015-07-24 |   7   |
like image 961
Zbigniew Kisły Avatar asked Sep 15 '15 15:09

Zbigniew Kisły


1 Answers

I think you want something like this:

SELECT
  SUM(added >= CURRENT_DATE() - INTERVAL 14 DAY) AS last_14_days,
  SUM(added >= CURRENT_DATE() - INTERVAL 7 DAY) AS last_7_days,
  SUM(added = CURRENT_DATE()) AS today
FROM users
WHERE
  added >= CURRENT_DATE() - INTERVAL 14 DAY

you can also use it for counting all records before < "2015-07-30" and the last 7 days, but it will have bad performances, I would suggest you to use inline queries instead:

SELECT
  (SELECT COUNT(added) FROM users WHERE added < "2015-07-30") AS before_30,
  (SELECT COUNT(added) FROM users WHERE added >= "2015-09-08") AS last_7

or an UNION query:

SELECT "Before 30" as Interval, COUNT(*) AS total
FROM users WHERE added < "2015-07-30"
UNION ALL
SELECT "Last 7" as Interval, COUNT(*) AS total
FROM users WHERE added >= "2015-09-08"

Edit

Based on your comment, you need to use a GROUP BY query. If added is a date field (with no time information) you can use this query:

SELECT added, COUNT(*)
FROM users
WHERE added >= CURRENT_DATE() - INTERVAL 7 DAY
GROUP BY added

Edit

This should be what you are looking for:

SELECT d.added, COUNT(*)
FROM
  (SELECT DISTINCT added
   FROM users
   WHERE added BETWEEN "2015-07-30" - INTERVAL 30 DAY AND "2015-07-30") AS d
  INNER JOIN users
  ON users.added <= d.added
GROUP BY
  d.added
ORDER BY `d`.`added` DESC

SQLFiddle here

like image 117
fthiella Avatar answered Nov 06 '22 00:11

fthiella