【问题标题】:SQL Server query to get the data from previous month if the column value is not present in next month如果列值在下个月不存在,SQL Server 查询以获取上个月的数据
【发布时间】:2021-05-31 18:40:36
【问题描述】:

我有一张表,其中包含每个月餐厅的许多菜单项。 并且只要项目数量发生变化,表格就会更新。

我想换个表或者做一个新表来获取每个月物品的价值。

例如。 如果最近一个月是四月

Restaurant Number of items Month
A 20 1/1/2021
A 15 1/21/2021
B 12 1/1/2021
C 30 2/1/2021
A 22 3/31/2021
B 15 4/1/2021

我希望新表中包含上述行加上缺失月份的数据与上个月相同

Restaurant Number of items Month
A 20 1/1/2021
A 15 1/21/2021
A 15 2/21/2021
A 22 3/1/2021
A 22 4/1/2021
B 12 1/1/2021
B 12 2/1/2021
B 12 3/1/2021
B 15 4/1/2021
C 30 2/1/2021
C 30 3/31/2021
C 30 4/1/2021

感谢大家的帮助

【问题讨论】:

  • month的数据类型是什么?

标签: sql sql-server sql-query-store


【解决方案1】:

这回答了问题的原始版本。

假设month 存储为带有每月第一天的日期,那么一个简单的方法使用递归 CTE:

with cte as (
      select restaurant, num_items, month,
             dateadd(month, -1,
                     coalesce(lead(month) over (partition by restaurant order by month),
                              max(month) over ()
                             )
                    ) as end_month
      from t
      union all
      select restaurant, num_items, dateadd(month, 1, month), end_month
      from cte
      where month < end_month
     )
select *
from cte
order by restaurant, month;

Here 是一个 dbfiddle。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 2019-07-02
    • 2014-03-21
    相关资源
    最近更新 更多