从查询中的子集获取最新记录

时间:2013-01-17 09:07:38

标签: sql sql-server sql-server-2005

我有两张相关的表格。

Table 1:
recordid | OrderNumber | MobileNumber
       1 | 1234        | 9999999999
       2 | 1234        | 9888888888
       3 | 1234        | 9777777777
       4 | 5433        | 9666666666
       5 | 1444        | 9555555555
       6 | 1444        | 9444444444
       7 | 1544        | 9333333333
       8 | 1632        | 9222222222


Table 2
recordid | modifiedon
       1 | 15/1/2013
       2 | 17/1/2013 
       3 | 13/1/2013
       4 | 10/1/2013
       5 | 16/1/2013
       6 | 01/1/2013 
       7 | 09/1/2013
       8 | 08/1/2013

我想要做的是获得一组独特的OrderNumber及其对应的MobileNumbers。如果一个OrderNumber有多个记录,则查询应获得最新修改记录的OrderNumberMobileNumber

所以基本上我应该得到以下结果。

OrderNumber | MobileNumber
1234        | 9888888888
5433        | 9666666666
1444        | 9555555555
1544        | 9333333333
1632        | 9222222222

我试过了

select OrderNumber, MobileNumber from Table1 
where OrderNumber in 
(
   Select Distinct table1. rderNumber, table2.ModifiedOn 
   from Table1, Table2 
   group by table2.ModifiedOn desc
) 

这很紧急,我会非常非常地收到快速回复。

2 个答案:

答案 0 :(得分:2)

使用CTEROW_NUMBER

会更容易
WITH cte AS 
(SELECT t1.ordernumber, 
        t1.mobilenumber, 
        RN = Row_number() 
               OVER ( 
                 partition BY t1.ordernumber 
                 ORDER BY t2, modifiedon DESC) 
         FROM   table1 t1 
                INNER JOIN table2 t2 
                        ON t1.recordid = t2.recordid) 
SELECT ordernumber, 
       mobilenumber
FROM   cte 
WHERE  rn = 1 

除此之外,您在DESC之后有GROUP BY

答案 1 :(得分:1)

select * 
from 
(
select t1.*, 
       row_number() 
       over (PARTITION BY t1.OrderNumber 
             ORDER BY t2.modifiedon DESC ) as rn
from t1
left join t2 on (t1.recordid=t2.recordid)
)
where RN=1