我有这个表:
表1:
id Name
1 Example1
2 Example2
表2:
id Date..............
1 5.2.2014........
1 6.2.2014.........
1 6.2.2014........
2 16.1.2014.......
2 17.1.2014.......
我需要从table1获取id和name并加入table1.id = table2.id并从table2只取前1行... 例如:
id Name Date
1 Example1 5.2.2014
2 Example2 16.1.2014
有可能吗?
答案 0 :(得分:1)
您可以row_number()
使用id
过滤除最新行以外的所有行:
select *
from (
select row_number() over (partition by id order by Date desc) as rn
, *
from Table2
) as t2
join Table1 as t1
on t1.id = t2.id
where t2.rn = 1 -- Only latest row
答案 1 :(得分:0)
嗯,一个简单的尝试就是
SELECT t1.*,
(SELECT TOP 1 t2.Date FROM Table2 t2 WHERE t2.ID = t1.ID t2.Date) t2Date
FROM Table1 t1
如果您使用的是SQL Server,则可以使用ROW_NUMBER
像
这样的东西;WITH Vals AS (
SELECT t1.ID,
t1.Name,
t2.Date,
ROW_NUMBER() OVER(PARTITION BY t1.ID ORDER BY t2.Date) RowID
FROm Table1 t1 LEFT JOIN
Table2 t2 ON t1.ID
)
SELECT *
FROM Vals
WHERE RowID = 1
答案 2 :(得分:-1)
Select t1.id, t1.name , MIN(t2.date)
From table1 t1
Inner Join table2 t2
On t1.id=t2.id
Group By t1.id, t1.name