Sql Server双子查询

时间:2009-10-08 07:13:41

标签: sql-server subquery

我有一张桌子,有点像历史性的桌子......所以我有这样的数据

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")

我觉得有一个更好的解决方案,但想不出来,我真的不喜欢在那里有两个子查询。

有什么建议吗?

2 个答案:

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

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