MrC*_*lan 0 sql sql-server join group-by sql-server-2008
我的数据库表是这样的:
#tblMain ID Value CreatedDate ________________________________________ 1 25 2011-10-11 14:00:45.910 1 20 2011-10-26 14:00:12.910 2 27 2011-10-14 14:00:32.910 2 39 2011-10-14 14:00:28.910 2 54 2011-10-17 14:00:27.910 3 67 2011-10-25 14:00:16.910 3 79 2011-10-25 14:00:02.910 4 34 2011-10-26 14:00:14.910 4 24 2011-10-26 14:00:06.910 4 88 2011-10-26 14:00:47.910 5 12 2011-10-26 14:03:14.910 5 34 2011-10-26 14:04:06.910 5 55 2011-10-26 14:04:47.910
我将从不同的表中获取ID列表.所以现在我想基于ID将上表加入到这个表中,这样我就可以为每个不同的ID获取1行,其中包含MIN(CreatedDate)行的值字段,即该特定ID的最旧值.即对于每一行,所选行将是:
SELECT TOP(1) * from #tblMain ORDER BY CreatedDate ASC where ID = 1
SELECT TOP(1) * from #tblMain ORDER BY CreatedDate ASC where ID = 2...and so on.
Run Code Online (Sandbox Code Playgroud)
因此,我的输出应该是这样的:
ID Value CreatedDate X Y Z(other columns from other tables) _______________________________________________________________________________ 1 25 2011-10-11 14:00:45.910 2 39 2011-10-14 14:00:28.910 3 79 2011-10-25 14:00:02.910 4 24 2011-10-26 14:00:06.910 5 12 2011-10-26 14:03:14.910
相信我,我已尽力尽可能清楚地表达我的要求,如果有什么不清楚的地方,请告诉我.期待快速反应.谢谢.
小智 5
尝试:
select m.ID, m.Value, m.CreatedDate, o.x, o.y, o.z
from (select tM.*, row_number() over (partition by ID order by CreatedDate) rn
from #tblMain tM) m
left join otherTable o on m.ID = o.ID
where m.rn=1
Run Code Online (Sandbox Code Playgroud)