Oracle中用于选择单行的Case语句

时间:2015-03-16 15:28:07

标签: oracle case

我有一个表'tblA',其中包含以下数据:

wuser_id wcompleted wstatusdate
123      1          10212014
123      0          11212014
456      0          02222014
456      0          03122014

我想基于wcompleted为wuser_id'123'选择wstatusdate,当wcompleted为1时我只需要选择'10212014', 对于'456',当wcompleted为0时,我只需要选择'03122014'。我的下面的查询为user_is 123返回两行。

以下是我正在做的事情,

select distinct wuser_id,
case wcompleted 
when 1
then max(wstatusdate)
when 0
then max(wstatusdate) 
end  
from tblA 
group by wuser_id, wcompleted

结果:

wuser_id wstatusdate
123      10212014
123      11212014
456      03122014

我需要结果:

wuser_id wstatusdate
123      10212014
456      03122014

2 个答案:

答案 0 :(得分:1)

使用分析函数row_number为每一行分配行号。完成后,您可以将其放入子查询中并选择第1行。这里有一些东西可以帮助你入门:

with tbla as (select 123 wuser_id, 1 wcompleted, to_date('10212014', 'mmddyyyy') wstatusdate from dual union all
              select 123 wuser_id, 0 wcompleted, to_date('11212014', 'mmddyyyy') wstatusdate from dual union all
              select 789 wuser_id, 1 wcompleted, to_date('10212014', 'mmddyyyy') wstatusdate from dual union all
              select 789 wuser_id, 1 wcompleted, to_date('12212014', 'mmddyyyy') wstatusdate from dual union all
              select 789 wuser_id, 0 wcompleted, to_date('11212014', 'mmddyyyy') wstatusdate from dual union all
              select 456 wuser_id, 0 wcompleted, to_date('02222014', 'mmddyyyy') wstatusdate from dual union all
              select 456 wuser_id, 0 wcompleted, to_date('03122014', 'mmddyyyy') wstatusdate from dual)
-- end of mimicking your tbla table.
select wuser_id,
       wcompleted,
       wstatusdate,
       row_number() over (partition by wuser_id
                          order by wcompleted desc, wstatusdate desc) rn
from   tbla;

  WUSER_ID WCOMPLETED WSTATUSDATE         RN
---------- ---------- ----------- ----------
       123          1 21-OCT-14            1
       123          0 21-NOV-14            2
       456          0 12-MAR-14            1
       456          0 22-FEB-14            2
       789          1 21-DEC-14            1
       789          1 21-OCT-14            2
       789          0 21-NOV-14            3

答案 1 :(得分:1)

您可以尝试以下内容:

SELECT wuser_id, wcompleted, wstatusdate FROM (
    SELECT wuser_id, wcompleted, wstatusdate, ROW_NUMBER() OVER ( PARTITION BY wuser_id ORDER BY wcompleted DESC, wstatusdate DESC ) AS rn
      FROM tblA
) WHERE rn = 1;

或者您可以执行以下操作:

SELECT wuser_id, MAX(wcompleted) AS wcompleted
     , MAX(wstatusdate) KEEP (DENSE_RANK FIRST ORDER BY wcompleted DESC) AS wstatusdate
  FROM tblA
 GROUP BY wuser_id;