根据条件从每组中排第一行

时间:2015-05-11 14:14:30

标签: sql sql-server sql-server-2008

Id Date
1 5/11/2015
1 5/11/2015
1 5/12/2015
1 5/13/2015
2 5/11/2015
2 5/11/2015
2 5/12/2015
2 5/13/2015
3 5/14/2015
3 5/15/2015
3 5/16/2015
3 5/17/2015
4 5/13/2015
4 5/13/2015
4 5/14/2015
4 5/15/2015


ID Name
1 Roy
2 Jame
3 Jani
4 Romi

我无法获得与第二个表匹配的第一行

我想通过ID获取每个表组中只有一行,其中日期大于今天的日期(即2015年11月5日),如下所示。

Id Name Date
1 Roy 5/12/2015
2 Jane 5/12/2015
3 Jani 5/14/2015
4 Romi 5/13/2015

2 个答案:

答案 0 :(得分:1)

使用cross applycorrelated subquery执行此操作

select * from Table2 t2
cross apply 
(select top 1 [date] from table1 t1
where t2.id = t1.id
AND t1.[date] > convert(date,getdate())
ORDER BY [date] ASC) CS 

SQLFIDDLE DEMO

答案 1 :(得分:0)

一种选择是使用row_number()

with cte as (
    select t2.id, t2.name, t1.date, 
           row_number() over (partition by t2.id order by t1.date) rn
    from table1 t1
        join table2 t2 on t1.id = t2.id 
    where t1.date > getdate())
select id, name, date
from cte
where rn = 1