同时应用Distinct和TOP(1)

时间:2012-03-16 09:40:36

标签: sql sql-server sql-server-2008 group-by join

我的数据库表是这样的:

#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.

因此,我的输出应该是这样的:

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

相信我,我已尽力尽可能清楚地表达我的要求,如果有不清楚的地方,请告诉我。期待快速反应。感谢。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

SELECT T1.ID,T1.Value,T1.CreateDate, T2Col1,..
FROM T2 INNER JOIN 
   (
     SELECT ID,Value,CreateDate,
         Row_Number() OVER (ORDER BY CreateDate) AS R1,
         Rank() OVER (ORDER BY CreateDate) AS R2
     FROM #tblMain
   ) T1 ON T2.ID = T1.ID
WHERE T1.R1 = T1.R2

答案 2 :(得分:0)

select
    Main.ID
    ,Main.Value
    ,Main.CreateDate
    ,MyOtherTable.X
    ,MyOtherTable.Y
    ,MyOtherTable.Z
from
    #tblMain Main
    inner join --this sub-query returns the unique ids with the min create dates
        (select
            ID
            ,MIN(CreateDate) as CreateDate
        from
            #tblMain
        group by
            ID) MinDates
        on MinDates.CreateDate = Main.CreateDate
            and MinDates.ID = Main.ID
    left join MyOtherTable
        on MyOtherTable.ID = Main.ID