2009-10-08 47 views
0

我有一個表,是有點像一個歷史悠久的表......所以我有這樣Sql Server的雙重子查詢

idA numberMov FinalDate
1 10 20090209
2 14 20090304
1 12 20090304
3 54 20080508
4 42 20090510
... ... ....數據

我需要根據每個IDA的最新finalDate檢索numberMov所以我用這個

select a.numberMov from (select idA, max(finalDate) maxDate from table1 group by idA) as b inner join table1 a on a.idA=b.idA and a.finalDate = b.maxDate

現在我有這樣

select m fields from n tables where n5.numberMov in ("insert first query here")

我覺得有一個更好的另一個查詢解決方案,但不能想到任何,我真的不喜歡有兩個子查詢在那裏。

有什麼建議嗎?

回答

0

沒有足夠的信息工作,以測試它自己,但這樣的事情可能會奏效。

select m fields 
from a inner join 
(select numberMov, 
    max(FinalDate) as maxDate 
from a 
group by numberMov) b 
    on a.numberMov = b.numberMov 
    and a.FinalDate = b.maxDate inner join 
n tables on a.numberMov = n.numberMov 
0

你不說SQL服務器的哪個版本,但是這將在SQL 2005+

;WITH rankCTE 
AS 
(
    SELECT idA 
      ,numberMov 
      ,FinalDate 
      ,ROW_NUMBER() OVER (PARTITION BY idA 
           ORDER BY FinalDate DESC 
          ) AS rn 
    FROM table1 
) 
,latestCTE 
AS 
(
    SELECT idA 
      ,numberMov 
      ,FinalDate 
    FROM rankCTE 
    WHERE rn = 1 
) 
SELECT m fields 
FROM n tables 
WHERE n5.numberMov IN (SELECT numberMov FROM latestCTE)