Fill In The Date Gaps With Date Table

前端 未结 4 1998
甜味超标
甜味超标 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:14

    Assuming that datetable includes every date of the year you can do with one simple CTE

    WITH OrdersCustomerDateBorders AS
    (
        SELECT CustomerID, MIN(fulldate) AS FirstOrderDate, MAX(fulldate) AS LastOrderDate
        FROM orders
        GROUP BY customer
    )
    select o.customer, d.fulldate, ISNULL(o.amount, 0) AS Amount
    from orders o
    INNER JOIN OrdersCustomerDateBorders OCDB ON OCDB.CustomerID = o.CustomerID
    INNER JOIN datetable d ON  ON d.fulldate between OCDB.FirstOrderDate AND OCDB.LastOrderDate
    WHERE d.calendaryear in (2012);
    

提交回复
热议问题