2017-10-04 99 views
0

我有以下查询,它会产生以下数据。 所有我想按字母顺序显示用户列表和First Record应该是All,All。SQL order by in union所有查询

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; 
+0

这里大部分人都希望格式化的文本,而不是图像。 – jarlh

+0

如果您使用此查询的结果放入下拉列表(例如),那么最好将“All,All”记录添加到代码列表中,而不是尝试在数据库中执行此操作。 –

+0

由于在'ABDUL'后''全部'是按字母顺序排列的,那么你需要一个不同的订单键,不是吗?你能想象你会怎么做?你需要添加另一列来排序,对吧? –

回答

1

ORDER BY使用CASE表达。

查询

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; 
+0

值得指出的是需要将原始SELECT转换为内联视图。当查询是select语句的UNION时,我们不能通过名称来引用列,而无需执行此操作。 – APC

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 
)