繁体   English   中英

SQL 中 CASE WHEN 中的数组搜索

[英]Array Search in a CASE WHEN in SQL

我目前有两张表的数据。 我根据某些调查结果按多个标准加入这两个表格。

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

我的问题是有时可能有 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

但这并不总是奏效。

表 b 中有一个字段,它是一个序列号,我想要具有更大序列号的反式类型,因为这是当天发生的最后一个。

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

我不知道如何告诉它抓住最大的一个。 我不一定说最后,因为数据被摄取的方式最大的 seq_num 可能是第一行或最后一行或两者之间的任何地方,因为它们在摄取到数据库中时没有任何顺序。

您可以使用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

说明 - 基于以下两个参数,每个窗口行将被赋予 rownumber,如 1,2,3...
partition by trans_type, trans_dt - 这将决定您的数据窗口。
order by trans_type, trans_dt, seq_num desc - 这将对窗口内的数据进行排序。 因此,具有最大 seq 的 seq num 将被编号为 1。

暂无
暂无

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

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