如何根据条件将列值动态替换为另一个值

时间:2019-10-01 12:25:38

标签: sql-server tsql

我正在尝试使用基于该人之前的房间号的选择查询来动态更改字段值。

下面是数据示例和我尝试过的查询。但这引发了一个错误,即内部查询返回了多个值。

      ,A.[Room],A.[CSR],A.[MemberShip],A.[NatCode]
      ,A.[MarketCode],A.[Adult],A.[Children],A.[ArrDate]
      ,A.[DepDate],A.[ResvStatus], CASE WHEN A.[Room]>9000 THEN (SELECT MIN(A.[Room])FROM [RESDETAILS] C WHERE C.GuestName=A.GuestName) ELSE A.[Room] END AS [Room]
  FROM [ITHAAFUSHI].[dbo].[RESDETAILS] A
  WHERE [GuestName]= 'Mr Jobin Joseph' 
   GROUP BY 
       A.[BusinessDate],A.[GuestName],A.[TravelAgent]
      ,A.[Room],A.[CSR],A.[MemberShip],A.[NatCode]
      ,A.[MarketCode],A.[Adult],A.[Children],A.[ArrDate]
      ,A.[DepDate],A.[ResvStatus]
  

“子查询返回了多个值。当   子查询遵循=,!=,<,<=,>,> =,或当子查询用作   表达式。”

Raw data

以下是“房间号”> 9000时的预期结果

Expected result

1 个答案:

答案 0 :(得分:0)

您的(SELECT MIN(A.[Room])FROM [RESDETAILS] C WHERE C.GuestName=A.GuestName) 返回多于1行,因此您需要在内部使用group by:

SELECT MIN(A.[Room])FROM [RESDETAILS] C WHERE C.GuestName=A.GuestName GROUP BY C.GuestName)