我有两个名为PassengerPaymentDetails
和RoomInfo
的表。以下是我用于从现有PassengerPaymentDetails
表中提取某些值的查询。
SELECT
COUNT(*) AS Count, RequestReference, RoomTypeID, RoomCategory
FROM
[UL_SLHEV].[dbo].[PassengerPaymentDetails]
WHERE
Status != 0
GROUP BY
RoomTypeID, RoomCategory, RequestReference
正如您所看到的,我在上面提到的表格中有RoomTypeID
,RoomCategory
和Count
。
以下屏幕截图包含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)
答案 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