同时应用Distinct和TOP(1)

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)

  • @PratikChandra:谢谢,我已经更正了省略的`()`.您是否缺少ID或特定ID的多行?如果是前者,听起来好像你的其他表没有所有ID的相应记录 - 更改为外连接(如在修改的查询中)应该解决这个问题.如果是后者,听起来好像其他表有一些ID的多个相应记录 - 在这种情况下,您需要优化其他表的链接条件. (2认同)