[英]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 ![]() |
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 ![]() |
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 ![]() |
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 ![]() |
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.