简体   繁体   中英

Oracle SQl Developer - Combining multiple rows into one row based on conditions

Is there a way to write a SQL query that would normally return multiple rows into one row depending on some conditions. Below is an example and desired results.

The query only returns the START & AGMTNUM when all the ACCTNUMs associated with that AGMTNUM are in Active STATUS.

table name Customer_Setup Example

Start      AGMTNUM      ACCTNUM      STATUS
12/1/16    AAAA         123456       ACTIVE
12/1/16    AAAA         789012       ACTIVE
12/1/16    AAAA         345675       PENDING 
7/1/16     BBBB         444444       ACTIVE
7/1/16     BBBB         555555       ACTIVE
8/1/16     CCCC         666666       PENDING
8/1/16     CCCC         777777       PENDING
8/1/16     CCCC         888888       PENDING
9/1/16     DDDD         999999       ACTIVE
9/1/16     DDDD         000000       ACTIVE

Expected results

START     AGMTNUM
7/1/16     BBBB  
9/1/16     DDDD     

Hmmm . . .

select start, agmtnum
from t
group by start, agmtnum
having min(status) = max(status) and min(status) = 'ACTIVE';

It is unclear whether start is part of the definition you want. You might want this slight variation:

select min(start), agmtnum
from t
group by agmtnum
having min(status) = max(status) and min(status) = 'ACTIVE';

Another way to do it:

select distinct "Start", agmtnum
from
  customer_setup c1
where
  not exists ( select * from customer_setup c2 where c1.agmtnum = c2.agmtnum and c2."STATUS" <> 'ACTIVE')
order by 1;

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