更新查询

时间:2017-10-06 09:10:43

标签: sql-server

我有两个名为PassengerPaymentDetailsRoomInfo的表。以下是我用于从现有PassengerPaymentDetails表中提取某些值的查询。

SELECT
    COUNT(*) AS Count, RequestReference, RoomTypeID, RoomCategory 
FROM 
    [UL_SLHEV].[dbo].[PassengerPaymentDetails]   
WHERE
    Status != 0 
GROUP BY 
    RoomTypeID, RoomCategory, RequestReference

正如您所看到的,我在上面提到的表格中有RoomTypeIDRoomCategoryCount

以下屏幕截图包含RoomInfo表:

我想从提取的RoomInfo表更新Passengerpaymentdetails表数据。我可以使用RequestReference映射这两个表。

需要根据RoomInfo表计数值更新Passengerpaymentdetails表中的计数值。有人可以帮忙吗?

更新

以下是我到目前为止尝试过的代码。它是正确返回连接表。我不知道如何使用获取表将值设置为RoomInfo表。而且我在这里也是出于某种目的使用左连接。如果左表包含带有新roomtypeId的新行,我也想插入该值。否则,如果右表包含相同的roomtypeID,则使用roomInfo表中的更新值更新passangerpaymentdetails

SELECT 
t1.RequestReference as RoomInfoReq, 
t1.Count as RoomInfoCount, 
t1.RoomTypeID as RoomInfoID,
t1.RoomCategory as RoomInfoRoomCat,
l.RequestReference as PassangerReq, 
l.Count as PassangerCount, 
l.RoomTypeID as PassangerRoomTypeID, 
l.RoomCategory  as PassangerRoomCategory

FROM (
select 
count(*) as Count, 
RequestReference, 
RoomTypeID, 
RoomCategory 
FROM
[UL_SLHEV].[dbo].[PassengerPaymentDetails]  
where 
Status!=0 group by RoomTypeID, RoomCategory, RequestReference) 

as t1
Left JOIN RoomInfo as l on 
t1.RequestReference = l.RequestReference and
t1.RoomTypeID = l.RoomTypeID and 
t1.RoomCategory = l.RoomCategory and
 l.Status!=0)

1 个答案:

答案 0 :(得分:0)

这样的事情。如果你提供DDL和DML指令来测试它会很好,但你可以看到逻辑如何做到这一点:

UPDATE ri
SET [COUNT] = rd.[COUNT]
FROM RoomInfo ri
JOIN (SELECT
    COUNT(*) AS [Count], RequestReference, RoomTypeID, RoomCategory 
FROM 
    [UL_SLHEV].[dbo].[PassengerPaymentDetails]   
WHERE
    Status != 0 
GROUP BY 
    RoomTypeID, RoomCategory, RequestReference) rd ON rd.RoomTypeID = ri.RoomTypeID
    AND rd.RoomCategory = ri.RoomCategory
    AND rd.RequestReference = ri.RequestReference