加入更多表

时间:2017-05-05 03:20:52

标签: sql-server join aggregate-functions

我使用以下查询获得总销售。

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]的错误结果。聚合函数返回错误的值,因为每个预订ID可能有多个AirTraveler,这是正确的。我该怎么做才能解决聚合函数问题?

我实际上被卡住了。

我正在使用SQL Server。

提前致谢。

1 个答案:

答案 0 :(得分: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,所以你的情况永远不会真实