如何从表中获取最后一条记录

时间:2012-11-13 22:17:44

标签: sql-server-2008 tsql

我有一张桌子:

表A

   ID (PK)(Identity seed)
   Key (nvarchar) (Unique Hashed Keys)

数据:

   ID          Key
   ----------- --------------------------------------------------
   1           ++0a4rZicJ68kProEpK/ig                            
   2           ++0Coy1S7szg3NjLi2kMLQ                            
   3           ++0eeYiZuRPxsiVVsBcfdg                            
   4           +F07I6n6kLvC/I98So8Y+w                            
   5           +f/RK7VMWIIo5IfUcMujmg  

表B :(没有PK)

   Content (nvarchar)
   SortKey (nvarchar) 

数据:

   Content          SortKey 
   ----------- --------------------------------------------------
   TEST1           ++0a4rZicJ68kProEpK/ig                            
   TEST2           ++0Coy1S7szg3NjLi2kMLQ                            
   TEST3           ++0eeYiZuRPxsiVVsBcfdg                            
   TEST4           +F/ZdeGRjbC4sP6ulQnOvg                            
   TEST5           +f0+6vJcwY++Xdx5lch1kQ 
   TEST6           +f/RK7VMWIIo5IfUcMujmg <-- Expected Result starts here
   TEST7           +F07I6n6kLvC/I98So8Y+w
   TEST8           +f0990bHYJUOXkyME+0kmg   

查询:

SELECT top 3 * 
FROM 
    TABLEB 
WHERE 
    SortKey > (SELECT top 1 Key 
               FROM TABLEA 
               ORDER BY ID DESC)
ORDER BY 
    SortKey 

以上查询给出了所需的结果,该结果大于SortKey(++ 1l32JdpYoHzXTCIp4jSA):

TEST6           +f/RK7VMWIIo5IfUcMujmg 
TEST7           +F07I6n6kLvC/I98So8Y+w
TEST8           +f0990bHYJUOXkyME+0kmg 

一旦我得到这个结果,我需要再次获得最后一个(最后一个记录)密钥以在另一个表上进行插入,所以我需要在这个场景中得到TEST8的密钥,即:f / RK7VMWIIo5IfUcMujmg。

如何在单个查询中执行此操作,而不必编写2个单独的查询?

1 个答案:

答案 0 :(得分:1)

您可以使用ROW_NUMBER()

WITH CTE AS 
(
SELECT
      ROW_NUMBER() OVER (ORDER BY CONTENT DESC) rn,
      Content,
      SortKey
FROM   tableb 
WHERE  sortkey < (SELECT TOP 1 [key] 
                  FROM   tablea 
                  ORDER  BY id DESC) 
 )
SELECT 
     Content,
     SortKey 
FROM CTE 
WHERE RN = 1

DEMO