首页 > 解决方案 > 当连续序列中的“空心”跟随时,如何标记记录?

问题描述

任务:拥有包含列的 SQL 表yearmonth(年和月均为整数;加上包含一些事实的列),当缺少下个月时,如何为记录设置标志?

动机,背景:用户应该填写缺失月份的事实值(考虑任何计划的值)。为了使工作更简单,我在 GUI 的行尾显示了一个图标。单击该图标将在下个月的意义上创建下一条记录。但是,年份和月份值是唯一键的一部分。如果下个月的记录已经存在,我不想提议创建下个月。这个想法是只为下个月记录不存在的行显示图标(以避免创建重复)。

例子:

year  month  flag      my comment
2020    1     0
2020    2     0
2020    3     1        icon should appear here because the next month (2020/4) should be created 
2020    5     0
2020    6     0
2020    7     0
2020    8     1        icon should appear because the month 9 and 10 are missing
2020   11     0
2020   12     0        December is followed by the next-year January, no icon 
2021    1     0
2021    2     0
2021    3     0
2021    5     0
2021    6     0
2021    7     1        the last record in the sequence -- show icon to create the next month

如何使用单个SELECT语句编写查询?在这种情况下,我使用的是 MS SQL 2014。

标签: sqlsql-server

解决方案


您可以使用lead()和一些算术:

select t.*,
       (case when lead(year*12 + month) over (order by year, month) = year*12 + month + 1
             then 0 else 1
        end) as flag
from t;

推荐阅读