sql - 当连续序列中的“空心”跟随时,如何标记记录?
问题描述
任务:拥有包含列的 SQL 表year
和month
(年和月均为整数;加上包含一些事实的列),当缺少下个月时,如何为记录设置标志?
动机,背景:用户应该填写缺失月份的事实值(考虑任何计划的值)。为了使工作更简单,我在 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。
解决方案
您可以使用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;
推荐阅读
- python - 从 Windows 终端执行 python 脚本时出现意外的语法错误
- java - 在 Java 中将对象列表写入 txt 文件的最快方法
- python - 如何通过 tf.Keras 使用 GPU 加速计算
- javascript - 开玩笑,测试一个输出字符串
- azure - 在 kubernetes 内的 server.xml 中设置环境变量
- reactjs - react-native-maps 自定义 Tiles 未显示
- jquery - window.resize,显示如何等待选项卡内容
- asp.net - 从 Web 窗体中的复合控件中的链接按钮获取单击事件
- sql - SQL左外连接表
- node.js - 在 nest.js 控制器中使用类验证器验证嵌套对象