SQL - 无效的标识符,但在哪里?

时间:2014-05-28 12:45:04

标签: sql oracle union

我是SQL的初学者,我现在一直在努力锻炼几个小时,现在问题是:

select to_char(date_Created, 'MON DD YYYY') as jours,  action, count(ID)
from Logs
group by action, to_char(date_Created, 'MON DD YYYY') 
union
select distinct to_char(date_Created, 'MON DD YYYY'), action, 0
from Logs
WHERE jours BETWEEN 'AVR.  14 2014' AND 'AVR.  15 2014'

当我尝试它时,它会返回错误:

ORA-00904: "JOURS" : identificateur non valide
00904. 00000 -  "%s: invalid identifier"
*Cause:    
*Action:
Erreur à la ligne 7, colonne 6

谢谢!

3 个答案:

答案 0 :(得分:3)

您的问题是由于标准SQL不允许您引用WHERE子句中的列别名而引起的。强制执行此限制是因为执行WHERE代码时,列值可能尚未确定。您无法使用“旅程”。标签,因为代码还没有意识到它。

答案 1 :(得分:1)

怎么样:

select to_char(date_Created, 'MON DD YYYY') as jours,  action, count(ID)
from Logs
group by action, to_char(date_Created, 'MON DD YYYY') 
union
select distinct to_char(date_Created, 'MON DD YYYY') as jours, action, 0
from Logs
WHERE to_char(date_Created, 'MON DD YYYY') BETWEEN 'AVR 14 2014' AND 'AVR 15 2014'

答案 2 :(得分:1)

SELECT中的问题是WHERE子句适用于最后SELECT,其中未定义jours。您可以通过将查询包装在另一个SELECT中来修复它,如下所示:

SELECT * FROM (
    -- Here is your original query without the WHERE clause
    select to_char(date_Created, 'MON DD YYYY') as jours,  action, count(ID)
    from Logs
    group by action, to_char(date_Created, 'MON DD YYYY') 
union
    select distinct to_char(date_Created, 'MON DD YYYY'), action, 0
    from Logs
) as inner
-- Here is your WHERE clause
WHERE jours BETWEEN 'AVR.  14 2014' AND 'AVR.  15 2014'

现在生成jours的查询已被包装,从WHERE子句引用该列是合法的。