简体   繁体   English

SQL 中 CASE WHEN 中的数组搜索

[英]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我的问题是有时可能有 2 个甚至三个 trans_Type,我尝试使用 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.表 b 中有一个字段,它是一个序列号,我想要具有更大序列号的反式类型,因为这是当天发生的最后一个。

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.我不一定说最后,因为数据被摄取的方式最大的 seq_num 可能是第一行或最后一行或两者之间的任何地方,因为它们在摄取到数据库中时没有任何顺序。

You can use window function.您可以使用window函数。

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...说明 - 基于以下两个参数,每个窗口行将被赋予 rownumber,如 1,2,3...
partition by trans_type, trans_dt - This will decide your window of data. partition by trans_type, trans_dt - 这将决定您的数据窗口。
order by trans_type, trans_dt, seq_num desc - This will order the data inside above window. order by trans_type, trans_dt, seq_num desc - 这将对窗口内的数据进行排序。 So, seq num with max seq will be numberd as 1.因此,具有最大 seq 的 seq num 将被编号为 1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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