0
我使用以下查詢獲取總銷售額。當加入更多表格時,聚合函數返回不正確的值
SELECT SUM([B].[TotalSale])
FROM [dbo].[BookingDetail] [BF] WITH (READPAST)
INNER JOIN [dbo].[Booking] [B] WITH (READPAST) ON [B].[BookingDetailID] = [BF].[ID]
WHERE [BF].[MarketID] = '2'
我想添加另一列來獲得總銷售額。 爲此,我必須與名爲AirTraveler的另一個表進行聯接。
但是,一旦我添加一個新表來查詢
SELECT
SUM([B].[TotalSale]) ,
SUM(CASE WHEN [B].[TravelSectorID] = 3 AND [B].[BookingStatusID] IN (16, 20, 22, 23) THEN COALESCE([B].[TotalSale], 0.0)
WHEN ([B].[TravelSectorID] = 1 AND [B].[IsDomestic] = 1 AND CONVERT(varchar, [AT].[FareDetails].query('string(/AirFareInfo[1]/PT[1])')) = 'FlightAndHotel') THEN [AT].[TotalSale]
ELSE 0 END) AS [GrossSale]
FROM [dbo].[BookingDetail] [BF] WITH (READPAST)
INNER JOIN [dbo].[Booking] [B] WITH (READPAST) ON [B].[BookingDetailID] = [BF].[ID]
LEFT OUTER JOIN [dbo].[AirTraveler] [AT] WITH(READPAST) ON [B].[ID] = [AT].[BookingID]
WHERE [BF].[MarketID] = '2'
它給的[TotalSale] .the聚合函數返回錯誤值,因爲有可能是每個訂單ID多AirTraveler,這是正確的不正確的結果。我能做些什麼來解決聚合函數問題?
我實際上被卡住了。
我正在使用SQL Server。
在此先感謝。
當然你的即使在此之前,總數也是正確的,因爲'bookingdetail'有很多行?無論如何,解決方案是使用'WHERE EXISTS'而不是加入。 –
@ Nick.McDermaid:使用WHERE EXISTS,我如何獲得[AT]的值[FareDetails] .query('string(/ AirFareInfo [1]/PT [1])')。你能編輯上述查詢嗎? –