简体   繁体   English

SQL 如果下个月的列值不存在,则服务器查询以获取上个月的数据

[英]SQL Server query to get the data from previous month if the column value is not present in next month

I have a table that contains a number of menu items in restaurants with respect to each month.我有一张桌子,其中包含每个月餐厅的许多菜单项。 and the table gets updated whenever there is a change in the number of items.并且只要项目数量发生变化,表格就会更新。

I want to change the table or make a new table to get the value of items for each month.我想更改表或制作一个新表以获取每个月的项目值。

For example.例如。 If latest month is April如果最近一个月是四月

Restaurant餐厅 Number of items项目数 Month
A一个 20 20 1/1/2021 2021 年 1 月 1 日
A一个 15 15 1/21/2021 2021 年 1 月 21 日
B 12 12 1/1/2021 2021 年 1 月 1 日
C C 30 30 2/1/2021 2021 年 2 月 1 日
A一个 22 22 3/31/2021 2021 年 3 月 31 日
B 15 15 4/1/2021 2021 年 4 月 1 日

I want the new table to have the above rows plus the missing months with same data as last month我希望新表具有上述行加上与上个月具有相同数据的缺失月份

Restaurant餐厅 Number of items项目数 Month
A一个 20 20 1/1/2021 2021 年 1 月 1 日
A一个 15 15 1/21/2021 2021 年 1 月 21 日
A一个 15 15 2/21/2021 2021 年 2 月 21 日
A一个 22 22 3/1/2021 2021 年 3 月 1 日
A一个 22 22 4/1/2021 2021 年 4 月 1 日
B 12 12 1/1/2021 2021 年 1 月 1 日
B 12 12 2/1/2021 2021 年 2 月 1 日
B 12 12 3/1/2021 2021 年 3 月 1 日
B 15 15 4/1/2021 2021 年 4 月 1 日
C C 30 30 2/1/2021 2021 年 2 月 1 日
C C 30 30 3/31/2021 2021 年 3 月 31 日
C C 30 30 4/1/2021 2021 年 4 月 1 日

Thanks for the help guys appreciated感谢帮助家伙赞赏

This answers the original version of the question.这回答了问题的原始版本。

Assuming that month is stored as a date with the first first day of the month, then a simple method uses recursive CTEs:假设该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 is a db<>fiddle. 是一个 db<>fiddle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM