将基于时间间隔的表格拆分为每日数据

时间:2018-11-22 12:47:02

标签: sql sql-server tsql datetime azure-sql-database

我正在尝试从基于间隔的表创建每日数据视图,如下所示:

startDate  |  endDate  | Product | Qty | Price |
2018-11-01   2018-11-30     A       12     10

这就是我希望视图中的结果为:

  Date     | Product  | Qty  | Price |
2018-11-01      A       12      10
2018-11-02      A       12      10
....
2018-11-30      A       12      10
2018-11-31      A        0       0  

如上所示,我想将时间间隔分成每日观察,如果在给定日期未购买产品A,则数量和价格应为0。

我创建了一个Calendar表来帮助我提出查询,但到目前为止还算不上成功。

我已经看过这些帖子,但是无法解决我的问题:

Break into multiple rows based on date range of a single row

https://dba.stackexchange.com/questions/168915/split-date-range-into-separate-records

generate days from date range

1 个答案:

答案 0 :(得分:3)

您有一个很棒的日历表。只需在LEFT JOIN的左侧使用它即可:

SELECT Calendar.Date, YourData.*
FROM Calendar
LEFT JOIN YourData ON Calendar.Date BETWEEN startDate AND endDate
WHERE Calendar.Date BETWEEN '2018-11-01' AND '2018-11-30'

如果要 所有 日期产品对,则添加CROSS JOIN:

SELECT Calendar.Date, Products.Product, YourData.*
FROM Calendar
CROSS JOIN (
    SELECT Product
    FROM YourData
    GROUP BY Product
) AS Products
LEFT JOIN YourData ON
    Calendar.Date BETWEEN startDate AND endDate AND
    Products.Product = YourData.Product
WHERE Calendar.Date BETWEEN '2018-11-01' AND '2018-11-30'