I think the rule can be simplified to this:
1, there must be one record for each partition (NO_FIRST,NO_MID,NO_LAST)
2, if sum of vol_count is 0 for each partition , then pick one record.
else eliminate the record with 'loc XXX' and 'vol_count 0'
So, plz try the following sql
Code:
select loc,no_first,no_mid,no_last,vol_count
from (
select t.*
,min(loc) over ( partition by no_first,no_mid,no_last ) as min_loc
,count(*) over ( partition by no_first,no_mid,no_last ) as cnt
,sum(VOL_COUNT) over ( partition by no_first,no_mid,no_last ) as tot
from t )
where ( cnt = 1 )
or ( tot = 0 and min_loc = loc )
or ( loc <> 'XXX' and vol_count <> 0 )
order by no_first, loc;
if db2 for z/os does not support olap function ,you can try this
Code:
select loc,no_first,no_mid,no_last,vol_count
from (
select t.loc,t.no_first,t.no_mid,t.no_last,t.vol_count
,t2.min_loc,t2.cnt,t2.tot
from t,
( select no_first,no_mid,no_last
,min(loc) as min_loc
,count(*) as cnt
,sum(VOL_COUNT) as tot
from t
group by no_first,no_mid,no_last ) t2
where t.no_first = t2.no_first
and t.no_mid = t2.no_mid
and t.no_last = t2.no_last )
where ( cnt = 1 )
or ( tot = 0 and min_loc = loc )
or ( loc <> 'XXX' and vol_count <> 0 )
order by no_first, loc;
and order by clause is not necessary.