0

我有一张桌子:

表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 个单独的查询?

4

1 回答 1

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

演示

于 2012-11-13T22:36:28.800 回答