0

I need help with some dates in mysql

I have this query that brings me the count of the messages of the corresponding dates of every message from the last 30 days.

SELECT DATE_FORMAT(time, '%m/%d/%Y') AS Dates, count(*) as count 
FROM ma_messages 
WHERE time BETWEEN NOW() - INTERVAL 30 DAY AND NOW() 
AND usersid_send = 110 
Group by Dates 
ORDER BY Dates ASC

query image

But I need that also bring me the other dates of the last 30 days with a value in the count of 0, for example that in the query also bring me 05/26/2021 date and the dates before 05/25/2021 and after 05/28/2021.

I don't know if this is possible, but I will apreciate any help.

Thanks.

pilcrow
  • 56,591
  • 13
  • 94
  • 135

3 Answers3

0

try this

SELECT 
DATE_FORMAT(time, '%m/%d/%Y') AS Dates, 
count(if(usersid_send='110',true,null)) as count 
FROM ma_messages 
WHERE time BETWEEN NOW() - INTERVAL 30 DAY AND NOW() 
Group by Dates 
ORDER BY Dates ASC
kilin
  • 1
  • Ok, it bring me like I said the 05/26/2021 date and also the 06/07/2021 date but the rest of the days of the last 30 days is not bring it, thank you anyways, maybe I can do something with this – Alexis Murillo Jun 08 '21 at 18:29
0

I have a table with dates .. with all the dates of the year – Alexis Murillo

SELECT d.`date`, COUNT(m.`time`) AS `count`
FROM dates_table d
LEFT JOIN ma_messages m ON d.`date` = DATE(m.`time`)
WHERE d.`date` BETWEEN NOW() - INTERVAL 30 DAY AND NOW() 
  AND m.usersid_send = 110 
GROUP BY d.`date`
ORDER BY d.`date` ASC
Akina
  • 39,301
  • 5
  • 14
  • 25
  • It doesn't bring me the other dates of the last 30 days with count 0, but at least it has the left join with the dates table, I appreciate anyways – Alexis Murillo Jun 08 '21 at 20:01
0

Using your table "with all the dates of the year":

WITH
message_counts AS (  SELECT DATE_FORMAT("time", '%m/%d/%Y') AS "day", 
                            COUNT(*) AS "count" 
                       FROM ma_messages 
                      WHERE "time" BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
                            AND
                            usersid_send = 110 
                   GROUP BY Dates)                         
   SELECT all_dates."day", COALESCE(message_counts."count", 0)
     FROM all_dates
LEFT JOIN message_counts
          ON all_dates."day" = message_counts."day"
    WHERE all_dates."day" BETWEEN BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
 ORDER BY all_dates."day" ASC
pilcrow
  • 56,591
  • 13
  • 94
  • 135