选择加入查询中的最新记录

时间:2013-05-28 12:39:09

标签: sql sql-server sql-server-2008 join

以下是我在一个表中更新管理器字段的查询。我面临的问题是我想在RH表中选择具有最新开始日期的用户(NRH.AffectedUserNumber)。

WITH [NewReqHeader]
AS
(SELECT ROW_NUMBER() 
           OVER(ORDER BY RH.StartDate DESC) AS rowid
          , RH.RequestId
          , RH.RequestType
          , RH.RequestStatusID
          , RH.AffectedUserNumber
          , RPD.TaskId
          , RPD.HotelID
          , RH.StartDate
      FROM DBO.RequestPermissionDetail RPD
           JOIN DBO.RequestHeader RH ON  RH.RequestId = RPD.RequestId
                    AND RH.RequestType = 2
                    AND RH.RequestStatusID = 20
                    AND RPD.TaskId = 923
)
UPDATE #Facility_Manager
SET    Manager = NRH.AffectedUserNumber
FROM   #Facility_Manager FM
       LEFT OUTER JOIN [NewReqHeader] NRH ON  FM.FacilityId = NRH.HotelID
                AND ISNULL(FM.FacilityId ,'') != ''
WHERE  FM.SecPermissionCount > 1

2 个答案:

答案 0 :(得分:2)

您需要在PARTITION BY函数中添加ROW_NUMBER子句以获取每个HotelID的计数。
然后将WHERE子句限制为

WHERE  FM.SecPermissionCount > 1 AND NRH.rowid = 1

答案 1 :(得分:0)

update fm
set 
  Manager = (
    select top 1 AffectedUserNumber
    from 
    NewReqHeader nrh
    where fm.FacilityID = nrh.HotelID
    order by StartDate desc
  )
from 
#Facility_Manager fm
where
SecPermissionsCount > 1