加入范围内的MAX日期

时间:2018-04-18 08:26:58

标签: sql oracle

我有两个表:DEALDEPTH(部门历史记录)

SELECT *
  FROM deal
       LEFT JOIN depth
         ON (    deal.dept_gid = depth_gid
             AND deal.deal_begin_date <= depth_end_date
             AND deal.deal_end_date >= depth_start_date)

但如果DEPTH中有一行符合条件&#34;同一dept_gid且范围必须相交&#34;然后我需要返回最大depth_end_date行。我该怎么办?

1 个答案:

答案 0 :(得分:2)

尝试在此处使用行号:

SELECT *
FROM
(
    SELECT d1.*, d2.*,
        ROW_NUMBER() OVER (PARTITION BY d1.dept_gid ORDER BY d2.depth_end_date DESC) rn
    FROM deal d1
    LEFT JOIN depth d2
        ON d1.dept_gid = d2.depth_gid AND
           d1.deal_begin_date <= d2.depth_end_date AND
           d1.deal_end_date >= d2.depth_start_date
) t
WHERE rn = 1