查询根据特定条件过滤记录

时间:2015-06-19 07:09:45

标签: sql oracle oracle11g

  

有一个表a_status_check,其中包含以下数据:

enter image description here

要求是:如果状态LC和BE都存在,则仅考虑LC。否则,考虑BE。忽略该ID的其他代码。

所以,结果应该是:

enter image description here

我尝试了DECODE和CASE功能而没有运气。有人可以帮忙。

4 个答案:

答案 0 :(得分:1)

使用分析功能:

select distinct
  id,
  first_value (status) over (partition by id order by status desc) status,
  first_value (amt   ) over (partition by id order by status desc) amt
from
  tq84_a_status_check
where
  status in ('LC', 'BE')
order by
  id;

TESTDATA:

create table tq84_a_status_check (
  id number,
  status varchar2(10),
  amt number
);

select distinct
  id,
  first_value (status) over (partition by id order by status desc) status,
  first_value (amt   ) over (partition by id order by status desc) amt
from
  tq84_a_status_check
where
  status in ('LC', 'BE')
order by
  id;

答案 1 :(得分:0)

你可以试试这个:

SELECT id, status, amt
FROM yourTable yt
INNER JOIN (
        -- get only max
        SELECT id, MAX(status) as status
        FROM yourTable
        GROUP BY id
    ) as onlyMax
      ON yt.id = onlyMax.id
      AND yt.status = onlyMax.status

答案 2 :(得分:0)

假设您只有两个STATUS值(A和B),此解决方案应该可以正常工作。我首先获得一个临时表,其中包含每个STATUS的{​​{1}}个计数,然后我ID将其返回JOINa_status_check子句在单独显示时会保留WHERE个记录,并在AB一起显示时保留A条记录。

B

答案 3 :(得分:0)

试试这个

SELECT id, status, amt
FROM a_status_check t
INNER JOIN (
        SELECT id, MAX(status) as status
        FROM a_status_check
        GROUP BY id
    ) as a
      ON t.id = a.id
      AND t.status = a.status