ORA-00904:与UNION ALL一起订购

时间:2015-02-27 10:11:51

标签: sql oracle-sqldeveloper

我正在创建一个带标题的平面文件。我收到了ORA-00904错误,我认为这是因为我创建的标题没有字段' employee_name' (我的假设是正确的吗?) 如果是,我如何在没有标题的情况下对查询进行排序?

我得到的错误:     

    ORA-00904: "employee_id":invalid identifier
    

我的代码:     

    select 'FILENAME' as filerec from dual
    UNION ALL
    select 'FILEDATE: ' || to_char(sysdate,'mm/dd/yyyy) as filerec from dual
    UNION ALL
    select employee_id || emloyee_name from employee_database as filerec
    order by employee_id;
    

这是我想要的输出:     

    FILENAME
    FILEDATE: 02/27/2015
    200125Ruth Chan
    200126Dan Gonzales
    200135Lisa Mayoral
    

3 个答案:

答案 0 :(得分:4)

SQL 中,您无法使用复合语句命名 ORDER BY 中的列,您必须使用列位置< /强>

或者,

明确投影列

在您的情况下,由于您已经连接了列,因此无法显式地对它们进行投影,而且列位置也没有任何意义。因此你可以玩一个小技巧。向需要先排序的行添加一个伪列,其中包含所需的值,然后在第一列之后要对其进行排序的伪列中使用 NULL 值。因此,NULL总是放在排序的末尾。

例如,

SQL> SELECT filerec FROM (
  2      SELECT 'FILENAME' AS filerec, 1 col FROM dual
  3      UNION ALL
  4      SELECT 'FILEDATE: ' || to_char(SYSDATE,'mm/dd/yyyy') as filerec, 2 col FROM dual
  5      UNION ALL
  6      SELECT empno || ename AS filerec, NULL col FROM emp
  7      ORDER BY 2,1
  8  );

FILEREC
--------------------------------------------------
FILENAME
FILEDATE: 02/27/2015
7369SMITH
7499ALLEN
7521WARD
7566JONES
7654MARTIN
7698BLAKE
7782CLARK
7788SCOTT
7839KING
7844TURNER
7876ADAMS
7900JAMES
7902FORD
7934MILLER

16 rows selected.

SQL>

答案 1 :(得分:1)

UNION的最后一部分放在括号中可能会起到作用:

select 'FILENAME' as filerec from dual
UNION ALL
select 'FILEDATE: ' || to_char(sysdate,'mm/dd/yyyy) as filerec from dual
UNION ALL
(select employee_id || emloyee_name from employee_database as filerec
    order by employee_id);

编辑:由于没有固有的顺序,更好的方法是:

select 'FILENAME' as filerec from dual
, 1 sortorder    
UNION ALL
select 'FILEDATE: ' || to_char(sysdate,'mm/dd/yyyy) as filerec from dual
, 2 sortorder
UNION ALL
select employee_id || emloyee_name from employee_database as filerec
, 3 sortorder
ORDER BY sortorder, filerec;

您可能需要将其放在子查询中,因为您可能不想选择属性sortorder。

答案 2 :(得分:0)

按列位置编号而不是列名称尝试排序

select 'FILENAME' as filerec from dual
UNION ALL
select 'FILEDATE: ' || to_char(sysdate,'mm/dd/yyyy) as filerec from dual
UNION ALL
select employee_id || emloyee_name from employee_database as filerec
order by 1;

或使用别名

select 'FILENAME' as filerec from dual
UNION ALL
select 'FILEDATE: ' || to_char(sysdate,'mm/dd/yyyy) as filerec from dual
UNION ALL
select employee_id || emloyee_name as filerec from employee_database 
order by filerec;