首页 > 解决方案 > 在查询中添加子查询 - 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 以外的所有日期

标签: sqloracle

解决方案


为另一个表中的日期生成月份中所有行的一种方法是使用递归 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。


推荐阅读