E
E
EvgMul2021-06-25 13:14:10
MySQL
EvgMul, 2021-06-25 13:14:10

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 shopsand usersboth tables have a field create_dateof 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 |
+---------------+------------+--------+

Is it possible to do this through sql and if possible, tell me how?
Thanks in advance to all who respond.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Akina, 2021-06-25
@EvgMul

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)

If you need data for a certain period - remove cte1 and cte2 , use the range boundaries in dates (the maxdate field is not needed, remove), add resp. WHERE to other CTEs.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question