sql - 在查询中添加子查询 - Oracle SQL
问题描述
我的查询返回一个月中的所有天。
SELECT
EXTRACT( DAY FROM day ) ||' '|| substr(TO_CHAR( day, 'fmDAY' ),0,3) AS day,
EXTRACT( DAY FROM day ) as day_id
FROM (
WITH temp ( col ) AS (
SELECT to_date(2, 'mm') --2 is February
FROM dual
)
SELECT col + level - 1 AS day
FROM temp
CONNECT BY level <= last_day(col) - col + 1
ORDER BY day
)
如何从查询中获取所有天数,其中 DAY_ID 不在 ==> 中(从 table1 中选择 day_id)
例如。表 1 返回 5,10,15
查询结果需要显示除 5,10,15 以外的所有日期
解决方案
为另一个表中的日期生成月份中所有行的一种方法是使用递归 CTE:
create table table1 as
select date '2021-04-16' as day_in from dual;
with cte (dte) as (
select trunc(day_in, 'MON') as dte
from table1
union all
select dte + interval '1' day
from cte
where dte < last_day(dte)
)
select *
from cte;
这是一个 db<>fiddle。
编辑:
如果您希望日期不在表格中,请使用:
with cte (dte) as (
select date '2021-02-01' as dte
from dual
union all
select dte + interval '1' day
from cte
where dte < last_day(dte)
)
select dte
from cte
where not exists (select 1 from table1 t1 where t1.day_id = cte.dte);
您也可以not exists
使用您的查询,但我发现递归 CTE 更易于遵循——而且它是标准 SQL。
推荐阅读
- javascript - Kibana 不显示从 Node.js Winston Logger 发送到 Elasticsearch 的日志
- php - 如果我使用 AWS RDS 将用户输入存储到数据库中,我的 PHP 文件应该放在哪里?
- java - 如何跟踪 Java 异常
- python - 在 Tkinter 中,有没有办法在运行程序时停止执行回调函数?
- c++ - 我如何计算向量[5][1] N 次
- json - Ionic - 带有 laravel json 响应的 API
- javascript - 如何使用 JS 控制 CSS 过渡和动画?
- c++ - 如何将按位运算符与 unsigned char 数据类型一起使用?
- python - 替换 np.array 中元素的更快方法
- c - 返回从 volatile 标量初始化的字符串表现得很奇怪?