1

I have the following table :

id site date id_action id_customer id_sim id_plq
7 mmg 2020-10-31 15:34:19 9 119
8 mmg 2021-10-31 15:34:29 9 119
11 mmg 2021-10-31 15:34:29 10 118
12 chrono 2021-10-31 18:31:29 9 118
13 mmg 2021-10-31 20:08:25 9 118
14 mmg 2021-09-30 21:09:14 9 118
15 plx 2020-10-30 21:09:14 9 119
16 plx 2021-10-31 22:12:45 12 118
17 plx 2020-10-31 22:12:45 9 118
18 plx 2021-10-31 22:12:45 9 118
19 plx 2021-08-31 22:12:45 9 118
20 plx 2021-10-31 22:12:45 9 119
21 plx 2021-07-27 22:12:45 9 116
22 plx 2021-10-31 22:12:45 9 118
23 plx 2021-06-28 22:12:45 9 118
24 plx 2020-10-31 22:12:45 9 119
25 plx 2020-06-30 22:12:45 9 118
26 plx 2020-10-31 22:12:45 9 118
27 plx 2020-10-31 22:12:45 9 119
28 plx 2020-10-31 22:12:45 9 118
29 plx 2020-08-31 22:12:45 9 118
31 chrono 2021-10-31 18:31:29 9 116

Actually I do the following request :

select YEAR(b.date) as year,
       MONTH(b.date) as month,
       b.site,
       count(distinct b.id) as 'totalLogin/Month',
       count(distinct b.ID_customer) as 'totalUser/Month'
from awm_logs b
group by year, month, site
order by year desc, month desc, site;

This give me this result :

year month site 'totalLogin/Month' 'totalUser/Month'
2021 10 chrono 2 2
2021 10 mmg 3 2
2021 10 plx 4 2
2021 9 mmg 1 1
2021 8 plx 1 1
2021 7 plx 1 1
2021 6 plx 1 1
2020 10 mmg 1 1
2020 10 plx 6 2
2020 8 plx 1 1
2020 6 plx 1 1

It is possible to insert the missing month in the result ? Without another table ?

And possibly the missing site ?

My idea of the result :

for avoiding long table i made the example with just the two first month

year month site 'totalLogin/Month' 'totalUser/Month' note
2021 10 chrono 2 2
2021 10 mmg 3 2
2021 10 plx 4 2
2021 9 chrono 0 0 new line
2021 9 mmg 1 1
2021 9 plx 0 0 new line

1 Answer 1

0

Build another table of all the needed dates, then do

SELECT ...
FROM dates AS d
LEFT JOIN your_table AS t ON t.date = d.date
....

dates could be manually created once, then kept for use. Or write code to generate. Or switch to MariaDB with its seq_1_to_100 type pseudo table.

5
  • ... + .. COALESCE(COUNT(..), 0) AS ..
    – Akina
    Commented Nov 1, 2021 at 5:40
  • So this is not possible without creating another table for the month and the site ? Even with a loop ?
    – Hadock
    Commented Nov 1, 2021 at 10:33
  • 1
    Yes, if you create a stored procedure with a loop. But frankly, it's much better to use a JOIN as Rick suggested. It's faster, less verbose, easier to maintain. Commented Nov 1, 2021 at 12:30
  • @Hadock - Alas it requires another table; I added to my Answer.
    – Rick James
    Commented Nov 1, 2021 at 14:52
  • Thanks for the precision @FedericoRazzoli
    – Hadock
    Commented Nov 2, 2021 at 7:04

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.