简体   繁体   中英

Selecting specific data based on a certain value

I have data like so:

Transaction#   Amount     Type
 123           $400.      C
 456          $400.      C
 456          $0.        A

Basically a C means an approved transaction, A means a reversed or edited transaction. So transaction 123 was approved, 456 was initially approved, then it was reversed to 0.

What I need is transactions that were “C” only. and if transactions were C and A, I want A. I've tried a self join, but was not successful. Using SQL, but in SAS (proc sql). I need the dollar amount of the transaction, but would like the whole row if possible. The output I would want are rows 1 and 3 in the example above

If you only need the transaction, you can use aggregation:

select transaction#
from t
group by transaction#
having min(type) = max(type) and min(type) = 'C';

If you want the original rows, I would recommend not exists :

select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.transaction# = t.transaction# and
                        t2.type <> 'C'
                 );

The way I understood your question this should do the trick (based on the fact that ordering strings is done alphabetically and A < C)

select transaction#, min(type)
from t
group by transaction#

It will result in

Transaction#    Type
 123               C
 456               A

Edit: Re-reading your request "The output I would want are rows 1 and 3 in the example above", I will build on Gordon's idea:

select t.*
from t
where not exists (select 1
                  from t t2
                  where t2.transaction# = t.transaction# and
                        t2.type ='A' and t.type <> 'A'
                 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM