【问题标题】:multiple joins to same sub query多个连接到同一个子查询
【发布时间】:2021-08-25 14:55:42
【问题描述】:

我需要反复加入同一张桌子,但这看起来很难看。任何建议表示赞赏。 下面是简化的 SQL,我在子查询中有 8 个表,它会产生许多相同日期的重复记录,所以我只需要为每个客户端找到最新的记录。(我不认为 DB和/或版本应该很重要,但我使用的是 DB2 11.1 LUW)

select c.client_num, a.eff_date, t.trx_date
from client c 
join address a on(a.id = c.addr_id)
join transaction t on(t.addr_id = a.id)
{many other joins}
where {many conditions};

select SQ.*
from [ABOVE_SUBQUERY] SQ
join
    (select client_num, max(eff_date) AS newest_date from [ABOVE_SUBQUERY] group by client_num) AA
    ON(SQ.client_num = AA.client_num and SQ.eff_date = AA.newest_date)
join
    (select client_num, max(trx_date) AS newest_date from [ABOVE_SUBQUERY] group by client_num) TT 
    ON(SQ.client_num = TT.client_num and SQ.trx_date = TT.newest_date)

【问题讨论】:

  • 谢谢@Gordon Linoff,效果很好。接受了答案,但它不会让我投票。

标签: sql join subquery


【解决方案1】:

我只需要对每个客户的最新记录进行罚款。

你不能只用row_number()吗?

select t.*
from (select t.*,
             row_number() over (partition by client_num order by eff_date desc, eff_time desc) as seqnum
      from <whatever> t
     ) t
where seqnum = 1;

【讨论】:

  • APPLY 操作也可能有效,如果这些都没有帮助,CTE 就是直接回答问题的方法。
  • 谢谢乔尔,我研究了公用表表达式 (CTE),这将更正确地回答我的问题。但是(尽管我不喜欢替代品作为答案)row_number() 建议消除了我对此的需求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-17
  • 2012-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多