Answer the question
In order to leave comments, you need to log in
Is it possible and how to make a query in the database to get statistical data?
I have the following task. There are two tables shops
and users
both tables have a field create_date
of type timestamp
. I need to get information about the number of rows added to these two tables by day. Those. as a result, I want to get a table like:
+---------------+------------+--------+
| Date | Shops | Users |
+---------------+------------+--------+
| 01.01.2020 | 123 | 215 |
| 02.01.2020 | 314 | 22 |
| 03.01.2020 | 18 | 45 |
+---------------+------------+--------+
Answer the question
In order to leave comments, you need to log in
WITH RECURSIVE
cte1 AS ( SELECT MIN(DATE(create_date)) mindate, MAX(DATE(create_date)) maxdate
FROM shops
UNION ALL
SELECT MIN(DATE(create_date)) mindate, MAX(DATE(create_date)) maxdate
FROM users ),
cte2 AS ( SELECT MIN(mindate) mindate, MAX(maxdate) maxdate
FROM cte1 ),
dates AS ( SELECT mindate thedate, maxdate
FROM cte2
UNION ALL
SELECT thedate + INTERVAL 1 DAY, maxdate
FROM dates
WHERE thedate < maxdate ),
shopstat AS ( SELECT DATE(create_date) thedate, COUNT(*) cnt
FROM shops
GROUP BY thedate ),
userstat AS ( SELECT DATE(create_date) thedate, COUNT(*) cnt
FROM users
GROUP BY thedate )
SELECT thedate `date`,
COALESCE(shopstat.cnt, 0) shops,
COALESCE(userstat.cnt, 0) users
FROM dates
LEFT JOIN shopstat USING (thedate)
LEFT JOIN userstat USING (thedate)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question