2012-03-16 60 views
0

我的數據庫表是這樣的:應用獨特的和TOP(1)一起

 
#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 

相信我,我已經盡我所能,以儘可能清楚地表達我的要求我可以,如果還有什麼不清楚的,請告訴我。期待快速響應。謝謝。

回答

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 
+0

您在row_number上缺少()。但即使執行此查詢後,我也不會得到不同的ID,即每個ID都有一行。 – MrClan 2012-03-16 11:32:52

+2

@PratikChandra:謝謝,我糾正了省略'()'。您是否缺少特定ID的ID或多行?如果前者,聽起來好像其他表沒有所有ID的相應記錄 - 更改爲外連接(如修改後的查詢中)應該修復該問題。如果是後者,聽起來好像你的其他表對多個ID有多個相應的記錄 - 在這種情況下,你需要改進其他表的鏈接標準。 – 2012-03-16 11:40:05

+0

@PratikChandra:如果沒有其他表,這個答案肯定會給你'#tblMain'中的所有不同的ID。所以,這個問題必須與其他表格一致,正如Mark已經爲您概述的那樣。 – 2012-03-16 11:57:50

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 
+0

它不工作。此查詢不僅僅獲取不同的ID,而我需要根據上述選擇標準爲每個ID創建一行。 – MrClan 2012-03-16 11:29:54

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