简体   繁体   中英

SQL order by in union all query

I have following query which produces following below data. All I want to show list of users in Alphabetically order and First Record should be All , All.

在此处输入图片说明

Query:

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;

Use a CASE expression in ORDER BY .

Query

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;

Perform the ORDER BY in a sub-query:

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
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM