Fill In The Date Gaps With Date Table

前端 未结 4 1994
甜味超标
甜味超标 2020-12-21 04:47

I have two tables.

An orders table with customer, and date. A date dimension table from a data warehouse.

The orders table does not contain activity for ev

4条回答
  •  甜味超标
    2020-12-21 05:31

    You can use recursive CTE to get all dates between two dates without need for datetable:

    ;WITH CTE_MinMax AS
    (
        SELECT Customer, MIN(DATE) AS MinDate, MAX(DATE) AS MaxDate
        FROM dbo.orders
        GROUP BY Customer
    )
    ,CTE_Dates AS
    (
        SELECT Customer, MinDate AS Date
        FROM CTE_MinMax
        UNION ALL
        SELECT c.Customer, DATEADD(DD,1,Date) FROM CTE_Dates c
        INNER JOIN CTE_MinMax mm ON c.Customer = mm.Customer
        WHERE DATEADD(DD,1,Date) <= mm.MaxDate
    )
    SELECT c.* , COALESCE(o.Amount, 0)
    FROM CTE_Dates c
    LEFT JOIN Orders o ON c.Customer = o.Customer AND c.Date = o.Date
    ORDER BY Customer, Date
    OPTION (MAXRECURSION 0)
    

    SQLFiddle DEMO

提交回复
热议问题