SQL join to correlated subquery where tables are related by overlapping ranges

不想你离开。 提交于 2019-11-29 16:01:35

You can do this utilizing a CTE and row_number().

SQL Fiddle Demo

;with cte as 
(
    SELECT *,
        ROW_NUMBER() OVER (PARTITION BY i.id ORDER BY e.EventDate DESC) as rNum
    FROM Item i
    JOIN Event e
        ON i.id between e.ItemStart and e.ItemEnd
)

SELECT ID,
  Name, 
  EventType,
  EventDate FROM cte
WHERE rNum = 1

Basically the CTE has joined item and event and added a new column for rownumber and is partitioned on item.ID. Here's a screenshot of what it looks like. From here I just select rNum = 1 which should be the max event date for each item.id.

This should be similar to other greatest-in-group and joining-on-range solutions:

SELECT * FROM 
  Item i INNER JOIN 
  Event e ON i.id BETWEEN e.ItemStart AND e.ItemEnd
WHERE NOT EXISTS ( -- exclude non-last events
   SELECT * FROM Event 
   WHERE 
      i.id between ItemStart and ItemEnd
      AND e.EventDate < EventDate)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!