简体   繁体   中英

Array Search in a CASE WHEN in SQL

I currently have two tables worth of data. I am joining the two tables on multiple criteria based on certain findings.

CASE WHEN a.trans_dt = b.trans_dt and b.trans_type = 'MASSTS' THEN b.trans_details

My problem is sometimes there may be 2 even three of the trans_Type, I tried using MAX

    MAX(CASE WHEN a.trans_dt = b.trans_dt and b.trans_type = 'MASSTS' 
    THEN b.trans_details ELSE NULL END) AS trans_Dtls

but that didn't always work.

There is a field in the table b, that is a seq number and I want the trans type with the greater seq number as that was the last one that occurred that day.

CASE WHEN a.trans_dt = b.trans_dt and b.trans_type = 'MASSTS' 
THEN b.trans_Details(with greatest b.seq_num) 

I am not sure how to tell it to grab the largest one. I can't necessarily say last because of the way the data gets ingested the largest seq_num could be the first row or the last row or anywhere in between as they are not in any order when ingested into the database.

You can use window function.

select a.blah.., b.blah...
from a
left join 
(select b.* , row_number() over ( partition by  trans_type, trans_dt order by trans_type, trans_dt, seq_num desc) as rn from b ) as b
ON b.rn=1 and a.trans_dt = b.trans_dt and b.trans_type = 'MASSTS' --This rn will give you data for maximum row from table b. Pls note to join on correct columns between a and b

Explanation - Based on below two parameters, each window rows will be given rownumber like 1,2,3...
partition by trans_type, trans_dt - This will decide your window of data.
order by trans_type, trans_dt, seq_num desc - This will order the data inside above window. So, seq num with max seq will be numberd as 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