SQL in order in union all query

时间:2017-10-04 12:40:50

标签: sql oracle

我有以下查询产生以下数据。 我只想按字母顺序显示用户列表,第一个记录应该是All,All。

enter image description here

查询:

SELECT 'All' created_by,
       'All' Prepby
FROM dual
UNION ALL
SELECT DISTINCT
       to_char(d.created_by) AS created_by,
       get_user_name(d.created_by) Prepby
FROM Hpml_Gp_dtl d
WHERE d.created_by IS NOT NULL
ORDER BY 2;

2 个答案:

答案 0 :(得分:1)

CASE中使用ORDER BY表达式。

<强>查询

select t.* from (
    select 'All' created_by, 'All' Prepby
    from dual
    union all
    select distinct to_char(d.created_by) as created_by,
    get_user_name(d.created_by) Prepby
    from Hpml_Gp_dtl d
    where d.created_by is not null
) t
order by case Prepby when 'All' then 1 else 2 end, Prepby;

答案 1 :(得分:0)

在子查询中执行ORDER BY

SELECT 'All' AS created_by,
       'All' AS Prepby
FROM   DUAL
UNION ALL
SELECT *
FROM   (
  SELECT DISTINCT
         to_char(created_by),
         get_user_name(created_by)
  FROM   Hpml_Gp_dtl
  WHERE  created_by IS NOT null
  ORDER BY 2
)
相关问题