2017-05-05 47 views
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。

在此先感謝。

+0

當然你的即使在此之前,總數也是正確的,因爲'bookingdetail'有很多行?無論如何,解決方案是使用'WHERE EXISTS'而不是加入。 –

+0

@ Nick.McDermaid:使用WHERE EXISTS,我如何獲得[AT]的值[FareDetails] .query('string(/ AirFareInfo [1]/PT [1])')。你能編輯上述查詢嗎? –

回答

0

沒有測試或任何東西,但是當你加入到導致一個頭表雙數的更低級表,你可以把它加入

之前,這可能是缺少一些打開/關閉支架預聚合它和別名,但希望你能做得出來

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 
     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 
(
SELECT BookingID, SUM(CASE WHEN 
CONVERT(varchar(50), [FareDetails].query('string(/AirFareInfo[1]/PT[1])')) 
= 'FlightAndHotel') THEN [TotalSale] ELSE 0 END) TotalSale 
FROM [dbo].[AirTraveler] [AT] WITH(READPAST) 
GROUP BY BookingID 
) AT 
ON [B].[ID] = [AT].[BookingID] 
WHERE [BF].[MarketID] = '2' 

而且我給你的VARCHAR蒙上了大小 - 我認爲,如果你不這樣做,這將是1,因此你的情況是不正確的