How do I include empty rows in a single GROUP BY DAY(date_field) SQL query?

后端 未结 4 1267
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-18 12:06

I\'m using MS SQL Server but welcome comparitive solutions from other databases.

This is the basic form of my query. It returns the number of calls per day from the

4条回答
  •  情深已故
    2021-01-18 12:52

    Can you create a table variable with the dates that you need and then RIGHT JOIN onto it? For example,

    DECLARE @dateTable TABLE ([date] SMALLDATETIME)
    
    INSERT INTO @dateTable
    VALUES('26 FEB 2009')
    INSERT INTO @dateTable
    VALUES('27 FEB 2009')
    -- etc
    
    SELECT 
      COUNT(*) AS "Calls",
      MAX(open_time),
      open_day
    FROM 
      (
    SELECT
     incident_id,
     opened_by,
     open_time - (9.0/24) AS open_time,
     DATEPART(dd, (open_time-(9.0/24))) AS open_day
       FROM incidentsm1
       RIGHT JOIN @dateTable dates
       ON incidentsm1.open_day = dates.date
       WHERE 
     DATEDIFF(DAY, open_time-(9.0/24), GETDATE())< 7
    
      ) inc1
    GROUP BY open_day
    

    The more ideal situation however, would be to have a table object with the dates in

提交回复
热议问题