Table_01:
----------------
ROW_ID | NAME
----------------
11223 | Frank
11224 | Frank
11225 | James
11226 | James
11227 | Joe
11228 | Joe
11229 | Joe
11230 | Tom
11231 | Tom
11232 | Tom
Table_02:
--------------------------------------------------
ROW_ID | NAME | EVENT_DATE | EVENT_LOCATION
--------------------------------------------------
11106 | Frank | 27/01/2017 | London
11109 | Frank | 19/01/2017 | Munich
11105 | James | 27/01/2017 | New York
11110 | James | 02/01/2017 | L.A
11101 | Joe | 27/01/2017 | Paris
11104 | Joe | 26/01/2017 | Barcelona
11107 | Joe | 31/01/2017 | Tokyo
11102 | Tom | 24/01/2017 | Prague
11103 | Tom | 03/01/2017 | Lisbon
11108 | Tom | 20/01/2017 | Dublin
我想为不同的用户查询 Table_01 ,并从 Table_02
了解他们最近的EVENT_DATE和EVENT_LOCATION答案:
---------------------------------------------------
NAME | NAME | EVENT_DATE | EVENT_LOCATION
---------------------------------------------------
Frank | Frank | 27/01/2017 | London
James | James | 27/01/2017 | New York
Joe | Joe | 31/01/2017 | Tokyo
Tom | Tom | 24/01/2017 | Prague
Microsoft SQL Server 2016.兼容级别:SQL Server 2005(90)
答案 0 :(得分:1)
您可以使用row_number()
:
select t2.*
from (select distinct name from table_01) n join
(select t2.*,
row_number() over (partition by name order by event_date desc) as seqnum
from table_02 t2
) t2
on n.name = t2.name and t2.seqnum = 1.
除非您想要进行过滤,否则您似乎真的不需要table_01
:
select t2.*
from (select t2.*,
row_number() over (partition by name order by event_date desc) as seqnum
from table_02 t2
) t2
where t2.seqnum = 1.
答案 1 :(得分:0)
除了on name
之外,我没有看到两个表如何加入。
有很多方法可以做到这一点。以下是其中一些:
with common_table_expression as ()
使用 row_number()
with cte as (
select u.Name, e.Event_Date, e.Event_Location
, rn = row_number() over (
partition by u.Name
order by e.[Event_Date] desc
)
from (select distinct Name from table_01) u
left join table_02 e
on u.Name = e.Name
)
select Name, Event_Location, Event_Date
from cte
where rn = 1
子查询而不是cte
:
select Name, Event_Location, Event_Date
from (
select u.Name, e.Event_Date, e.Event_Location
, rn = row_number() over (
partition by u.Name
order by e.[Event_Date] desc
)
from (select distinct Name from table_01) u
left join table_02 e
on u.Name = e.Name
) as sub
where rn = 1
cross
apply
版本:
select distinct
u.Name
, e.Event_Location
, e.[Event_Date]
from (select distinct Name from table_01) u
cross apply (
select top 1
Event_Date
, Event_Location
from table_02 e
where e.Name =u.Name
order by e.Event_Date desc
) as e;
top with ties
版本:
select top 1 with ties
u.Name, e.Event_Date, e.Event_Location
from (select distinct Name from table_01) u
left join table_02 e
on u.Name = e.Name
order by
row_number() over (
partition by u.Name
order by e.Event_Date desc
)