单个Oracle SQL查询中的奇偶数

时间:2018-09-30 10:49:51

标签: sql oracle oracle11g

我想要在单个查询中列出OddEven的数字,我只是发现奇数或偶数之一,下面是我的代码

SELECT * FROM 
 ( SELECT T.C_DATE,T.C_NAME,T.C_TIME,L_UID, ROWNUM RANK 
     FROM TENTER T)
    WHERE MOD(RANK,2)=1
      AND C_DATE BETWEEN :P_FROM_DATE AND :P_TO_DATE 
    ORDER BY L_UID, C_TIME ASC;

2 个答案:

答案 0 :(得分:2)

您应该能够在没有子查询的情况下执行此操作。假设您只希望每行有一个标签:

SELECT T.C_DATE, T.C_NAME, T.C_TIME, L_UID, ROWNUM as RANK,
       (CASE WHEN MOD(ROWNUM, 2) = 0 THEN 'EVEN' ELSE 'ODD' END) as even_odd_label 
FROM TENTER T
WHERE C_DATE BETWEEN :P_FROM_DATE AND :P_TO_DATE 
ORDER BY L_UID, C_TIME ASC;

答案 1 :(得分:1)

您可以使用:

SELECT decode(mod(TT.RANK,2),0,'Even','Odd') as rank,
       TT.*
  FROM 
 ( SELECT T.C_DATE,T.C_NAME,T.C_TIME,L_UID, 
          ROW_NUMBER() OVER (ORDER BY L_UID, C_TIME ASC) as RANK 
     FROM TENTER T) TT
    WHERE C_DATE BETWEEN :P_FROM_DATE AND :P_TO_DATE
    ORDER BY L_UID, C_TIME ASC;

P.S。顺便说一句,我建议您使用带有特定序号的ROW_NUMBER函数,而不是系统生成的ROWNUM伪列。