双列的选择条件(ORA-00904:标识符无效)

Selecting condition of a dual column (ORA-00904: Invalid identifier)

我有一个列表,其中包含双 table 生成的日期和数字,如下所示:

SELECT TO_CHAR (TO_DATE ('19-02-1984', 'DD-MM-RRRR') + LEVEL, 'DAY') DAY,
       LEVEL
  FROM DUAL
CONNECT BY LEVEL <= 7

它产生了这个 table:

DAY     | LEVEL |
-----------------
MONDAY      1
TUESDAY     2
WEDNESDAY   3
THURSDAY    4
FRIDAY      5
SATURDAY    6
SUNDAY      7

为什么不能像 WHERE WEEK_DAY = 'SATURDAY'?

这样的 select
SELECT TO_CHAR (TO_DATE ('19-02-1984', 'DD-MM-RRRR') + LEVEL, 'DAY') WEEK_DAY,
       LEVEL
  FROM DUAL
 WHERE WEEK_DAY = 'SATURDAY'
CONNECT BY LEVEL <= 7

它 return 错误消息 ORA-00904: 标识符无效,但我不明白为什么。

基本上,您不能在 WHERE 子句中引用 SELECT 子句中的 WEEK_DAY 别名,因为在计算 WHERE 子句时可能不知道它的值。这不是您的查询所独有的 - 这就是它的工作原理。

你有几个选择...

选项 1: 从 WHERE 子句中的 SELECT 子句重现计算:

SELECT TO_CHAR (TO_DATE ('19-02-1984', 'DD-MM-RRRR') + LEVEL, 'fmDAY') WEEK_DAY, LEVEL
  FROM DUAL
 WHERE TO_CHAR (TO_DATE ('19-02-1984', 'DD-MM-RRRR') + LEVEL, 'fmDAY') = 'SATURDAY'
CONNECT BY LEVEL <= 7

选项 2: 将您的查询移动到内联视图中并对其应用 WHERE 过滤器:

select * from (
  SELECT TO_CHAR (TO_DATE ('19-02-1984', 'DD-MM-RRRR') + LEVEL, 'fmDAY') WEEK_DAY, LEVEL LVL
    FROM DUAL
  CONNECT BY LEVEL <= 7 )
 where WEEK_DAY = 'SATURDAY' 

请注意,我还在 to_char() 函数中使用了 fmDay,因此日期名称中没有额外的填充。