对数字进行排序,将0作为最后一个优先级,PL / SQL关键字作为优先级

时间:2013-12-12 14:02:41

标签: asp.net oracle sorting plsql

我有:

PROCEDURE A
(
    inId    IN NUMBER,
    RC1           OUT SYS_REFCURSOR
) IS
tMessage VARCHAR2(128);

BEGIN
    OPEN RC1 FOR
           SELECT * FROM 
           (  
                  SELECT 
                         a.company,
                  SUM(a.holding_balance) balance
                  FROM  TableNameEntries A

                   WHERE
                        A.BATCH_ID = inId 
                   GROUP BY a.company        
           )
                   ORDER BY balance DESC  ; 

    EXCEPTION
        WHEN OTHERS THEN
             tMessage :='Exception ' || SQLCODE || ': ' || SQLERRM;            
    OPEN RC1 FOR
    SELECT tMessage FROM DUAL;

END A;

对于balance列,我的值为-1,0,1。目前它的排序类似于1 0 -1,但我不关心零,所以我希望它像-1,1,0或1,-1,0

我如何在PL / SQL中执行此操作?我试过了:

 SELECT 
                         a.company,
                  SUM(a.holding_balance) balance
                  FROM  REC.CAG_GL_ENTRIES A

                   WHERE
                        A.BATCH_ID = 201311 
                   order by case priority when 0 then 2 else 1 END   priority

但是它说PRIORITY是无效的标识符。

我怎样才能让它发挥作用?

4 个答案:

答案 0 :(得分:1)

尝试:

ORDER BY CASE balance 
            WHEN 0 THEN null
            ELSE balance
         END 
      DESC NULLS LAST

答案 1 :(得分:0)

在你的情况下有两种方式(第二种更常见,第一种更清楚):

SELECT a.company,
       SUM(a.holding_balance) balance
FROM  REC.CAG_GL_ENTRIES A
WHERE A.BATCH_ID = 201311 
order by abs(balance) desc;

SELECT a.company,
       SUM(a.holding_balance) balance
FROM  REC.CAG_GL_ENTRIES A
WHERE A.BATCH_ID = 201311 
order by decode(balance,1,1,-1,1,2);

答案 2 :(得分:0)

ORDER BY SIGN(ABS(balance)) DESC, balance

ABS()将所有底片变为正面。 SIGN()将0变为0,> 0变为1(并且< 0至-1)。结合DESC,这将所有零都放在最后,并且所有非零都在它们之上,没有特定的顺序。 然后我再次按天平排序以订购非零。

答案 3 :(得分:0)

您也可以使用

order by balance * balance desc