0

下面是我在一个表中更新管理器字段的查询。我面临的问题是我想在 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
4

2 回答 2

2

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

WHERE  FM.SecPermissionCount > 1 AND NRH.rowid = 1
于 2013-05-28T13:21:24.203 回答
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
于 2013-05-28T12:50:55.770 回答