我有两个表:DEAL
和DEPTH
(部门历史记录)
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
行。我该怎么办?
答案 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