How to fill in blanks in a date in MySQL?

How can I fill in the blanks in a date in MySQL? Here is my request:

SELECT DATE (posted_at) AS date,
    COUNT (*) AS total,
    SUM (attitude = 'positive') AS positive,
    SUM (attitude = 'neutral') AS neutral,
    SUM (attitude = 'negative') AS negative
    FROM `messages`
    WHERE (`messages`.brand_id = 1)
    AND (`messages`.`spam` = 0
    AND `messages`.`duplicate` = 0
    AND `messages`.`ignore` = 0)
    GROUP BY date ORDER BY date

It returns the correct set of results, but I want to fill the gaps between the start and end dates with zeros. How can i do this?

+3
source share
2 answers

start end, LEFT JOIN :

SELECT  d.dt AS date,
        COUNT(*) AS total,
        SUM(attitude = 'positive') AS positive,
        SUM(attitude = 'neutral') AS neutral,
        SUM(attitude = 'negative') AS negative
FROM    dates d
LEFT JOIN
        messages m
ON      m.posted_at >= d.dt
        AND m.posted_at < d.dt + INTERVAL 1 DAYS
        AND spam = 0
        AND duplicate = 0
        AND ignore = 0
GROUP BY
        d.dt
ORDER BY
        d.dt

, .

MySQL - , .

PostgreSQL generate_series, Oracle SQL Server (CONNECT BY CTE s, ).

+4

, MySQL ; , .

--Inputs
declare @FromDate datetime, /*Inclusive*/
        @ToDate datetime    /*Inclusive*/
set @FromDate = '20091101'
set @ToDate = '20091130'

--Query
declare @Dates table (
    DateValue datetime NOT NULL
)
set NOCOUNT ON
while @FromDate <= @ToDate /*Inclusive*/
begin
  insert into @Dates(DateValue) values(@FromDate)
  set @FromDate = @FromDate + 1
end
set NOCOUNT OFF

select  dates.DateValue,
        Col1...
from    @Dates dates
        left outer join SourceTableOrView data on
            data.DateValue >= dates.DateValue
        and data.DateValue < dates.DateValue + 1 /*NB: Exclusive*/
where   ...?
0

Source: https://habr.com/ru/post/1725234/


All Articles