2017-10-06 10 views
0

PassengerPaymentDetailsRoomInfoという2つのテーブルがあります。以下は、既存のPassengerPaymentDetailsテーブルからいくつかの値を抽出するために使用したクエリです。更新クエリの問題

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

あなたは私は上記の表にRoomTypeIDRoomCategoryCountを持って見ることができるように。

は、私が抽出されたPassengerpaymentdetailsテーブルからRoomInfoテーブルのデータを更新する:

次のスクリーンショットは、RoomInfoテーブルを持っています。私はRequestReferenceでこれらの2つのテーブルをマップできます。

RoomInfoテーブルのカウント値をPassengerpaymentdetailsテーブルカウント値に従って更新する必要があります。誰でも助けてくれますか?

UPDATE

以下は、私がこれまで試してみましたコードです。それは正しくリターン結合テーブルです。私はテーブルを取得することによって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

何かがそうです。それをテストするために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