如何根据其他值选择值?

时间:2019-04-03 18:24:44

标签: sql oracle plsql

我需要查找没有'0'的不同acct_number的列表作为Status_code。 我的表中有以下记录:

Acct_number   Status_code 
 1234              0
 1234              1
 1234             -1
 2345              2
 2345              3
 2345             -1
 3456              3
 3456              0
 3456              -1

我想像这样:

 acct_number
  2345     

1234和3456都将“ 0”作为status_code。 2345是唯一一个不具有“ 0”作为status_code的代码

我的查询看起来像这样,但没有给出正确的结果:

 with cte as(
 select distinct acct_number,count(distinct status_code)  
 from  XXX
 where ---------
 and status_code<>'0'
 group by acct_number
 having count(distinct status_code) >1)
      select  distinct sk.acct_number, a.acct_number, sk.status_code 
      from  XXX b, cte a
      where -----
      and  b.status_code<>'0'
      and b.acct_number=a.acct_number;

4 个答案:

答案 0 :(得分:2)

我将聚合用作:

select Acct_number
from t
group by Acct_number
having sum(case when status_code = 0 then 1 else 0 end) = 0;

或者,如果您有单独的帐户表,则:

select a.*
from accounts a
where not exists (select 1
                  from account_status acs
                  where acs.acct_number = a.acct_number and acs.status_code = 0
                 );

答案 1 :(得分:1)

仅与众不同就足够了

select distinct Acct_number from table_name where Status_code <> '0';

答案 2 :(得分:0)

不存在

select t1.* from XXX t1
 where not exists ( select 1 from 
                   XXX t2 where t2.Acct_number=t1.Acct_number
                    and Status_code=0)

或者您可以使用聚合

select Acct_number
from XXX
group by Acct_number
having sum(case when Status_code = 0 then 1 else 0 end)<>1

答案 3 :(得分:0)

您可以使用not exists子句消除所有至少有一条状态码为0的记录的帐户。

select distinct X1.acct_number  
     from  XXX as X1
     where not exists (select 1 from XXX as X2
     where X2.status_code=0
    and x2.acct_number=x1.acct_number)