基于字符串别名值排序

时间:2016-12-02 07:50:21

标签: sql oracle

我有如下查询。我想要的是将DESCRIPTION的别名设为'Qty'作为第一个。

SELECT   'Net Others' AS DESCRIPTION,
          AREA_ID FROM SALES
UNION ALL
SELECT   'Qty' AS DESCRIPTION,
          AREA_ID FROM SALES
UNION ALL
SELECT   'Sales Others' AS DESCRIPTION,
          AREA_ID FROM SALES
UNION ALL
SELECT   'Discount Others' AS DESCRIPTION,
          AREA_ID FROM SALES

我尝试添加

order by case when DESCRIPTION= 'QTY' then 1 end

它来了错误

  

ORDER BY项必须是SELECT列表表达式的编号

我尝试已经这样做也不起作用

order by (DESCRIPTION|| 'Qty') ASC

那么如何通过这种情况下订单呢? 我搜索谷歌,但我没有像我的情况。信息我使用Oracle数据库。

2 个答案:

答案 0 :(得分:1)

请试试这个:

select DESCRIPTION ,AREA_ID 
from 
   (
    SELECT   'Net Others' AS DESCRIPTION,
              AREA_ID FROM SALES
    UNION ALL
    SELECT   'Qty' AS DESCRIPTION,
              AREA_ID FROM SALES
    UNION ALL
    SELECT   'Sales Others' AS DESCRIPTION,
              AREA_ID FROM SALES
    UNION ALL
    SELECT   'Discount Others' AS DESCRIPTION,
              AREA_ID FROM SALES
    )         
 ORDER BY DECODE(DESCRIPTION,'Qty',1);

演示:

select DESCRIPTION ,AREA_ID 
from 
   (
    SELECT   'Net Others' AS DESCRIPTION, 'AREA_ID' AREA_ID
    FROM DUAL
    UNION ALL
    SELECT   'Qty' AS DESCRIPTION, 'AREA_ID'  AREA_ID
    FROM DUAL
    UNION ALL
    SELECT   'Sales Others' AS DESCRIPTION,  'AREA_ID' AREA_ID
    FROM DUAL
    UNION ALL
    SELECT   'Discount Others' AS DESCRIPTION, 'AREA_ID' AREA_ID
    FROM DUAL
    )         
 ORDER BY DECODE(DESCRIPTION,'Qty',1)

输出:

DESCRIPTION     AREA_ID
--------------- -------
Qty             AREA_ID
Discount Others AREA_ID
Sales Others    AREA_ID
Net Others      AREA_ID

答案 1 :(得分:0)

我认为问题是你在AS之后拿了两个名字,看起来首先是名字。

尝试这样的事情

SELECT 'Net Others' AS AREA_ID FROM SALES
etc...

希望有所帮助