2

我有两个相关的表。

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. 如果 1 有多个记录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
) 

这很紧急,如果能得到快速回复,我将非常高兴。

4

2 回答 2

2

CTE使用and更容易ROW_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.

于 2013-01-17T09:10:16.630 回答
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
于 2013-01-17T09:18:29.690 回答