Oracle 中用于选择单行的案例语句

Case statement in Oracle for selecting single row

我有一个 table 'tblA' 具有以下数据:

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

我想 select wstatusdate for wuser_id '123' 基于 wcompleted,当 wcompleted 为 1 时我只需要 select '10212014', 对于“456”,当 wcompleted 为 0 时,我只需要 select“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

使用解析函数row_number为每一行分配一个行号。一旦你有了它,你就可以把它放在子查询中,select 第一行。这里有一些可以帮助您入门的东西:

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

您可以尝试如下操作:

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;