sql - SQL 仅选择缺少的月份
问题描述
请注意,输出中缺少 2017-04-01、2018-02-01、2018-07-01 和 2019-01-01 月份。我只想显示那些缺失的月份。有谁知道该怎么做?
询问:
SELECT TO_DATE("Month", 'mon''yy') as dates FROM sample_sheet
group by dates
order by dates asc;
输出:
2017-01-01
2017-02-01
2017-03-01
2017-05-01
2017-06-01
2017-07-01
2017-08-01
2017-09-01
2017-10-01
2017-11-01
2017-12-01
2018-01-01
2018-03-01
2018-04-01
2018-05-01
2018-06-01
2018-08-01
2018-09-01
2018-10-01
2018-11-01
2018-12-01
2019-02-01
2019-03-01
2019-04-01
解决方案
我不了解 Vertica,所以我在 Microsoft SQL Server 中编写了一个工作概念证明,并尝试根据在线文档将其转换为 Vertica 语法。
它应该如下所示:
with
months as (
select 2017 as date_year, 1 as date_month, to_date('2017-01-01', 'YYYY-MM-DD') as first_date, to_date('2017-01-31', 'yyyy-mm-dd') as last_date
union all
select
year(add_months(first_date, 1)) as date_year,
month(add_months(first_date, 1)) as date_month,
add_months(first_date, 1) as first_date,
last_day(add_months(first_date, 1)) as last_date
from months
where first_date < current_date
),
sample_dates (a_date) as (
select to_date('2017-01-15', 'YYYY-MM-DD') union all
select to_date('2017-01-22', 'YYYY-MM-DD') union all
select to_date('2017-02-01', 'YYYY-MM-DD') union all
select to_date('2017-04-15', 'YYYY-MM-DD') union all
select to_date('2017-06-15', 'YYYY-MM-DD')
)
select *
from sample_dates right join months on sample_dates.a_date between first_date and last_date
where sample_dates.a_date is null
Months是一个递归动态表,包含自 2017-01 以来的所有月份,包括该月的第一天和最后一天。sample_dates只是用于测试逻辑的日期列表 - 您应该将其替换为您自己的表格。
一旦您构建了该月历表,您需要做的就是使用外部查询检查您的日期,以查看哪些日期不在first_date和last_date列之间的任何时期之间。
推荐阅读
- python - pydantic无法区分整数和字符串
- python - 在 PyQt5 中找到多个随机创建的小部件(如 QLabel、QPushButton 等)的 mousepress 事件的父级
- php - preg_replace 替换两个符号之间多行的换行符
- docker - kind - Kubernetes pod 无法从私有 Docker 注册表中提取图像
- javascript - 仅将第一行粘贴到 Javascript 提示符中,但复制所有行
- node.js - OAuth2 - 错误 400:redirect_uri_mismatch 与 Passport,重定向 URL 与设置的不同
- python - 从当前进程创建 PM2 生态系统文件
- python - AttributeError:模块“pydotplus”没有属性“graph_from_dot_data”
- list - 在 Prolog 中查找列表中列表的长度
- android - WebView 有时显示白色空白页,有时显示文件