Question : Need a solution for Sum within a Sum

Hello Experts,

I have a query that needs to get the sum or a sum.  SQL doesn't seem to like doing that.  Is there some clever way that I can rewrite this so I don't get the evil:  

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

Thanks,
Moe
1:
SUM(ISNULL(CASE WHEN A.[Type] = 'NEW' THEN (a.revenue * e.To_USD_Rate / SUM(a.Leg)) END, 0)) - SUM(ISNULL(CASE WHEN a.[Type] = 'CAN' THEN (a.revenue * e.To_USD_Rate / SUM(a.Leg)) END, 0)) AS 'Rev / Res'

Answer : Need a solution for Sum within a Sum

Can you try this:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
SELECT [Year], [Month], Loc, [Total Bookings], [Revenue in USD], [Revenue in USD] / Leg_sum as 'Rev / Res'
FROM (
SELECT b.Year, 
DateName(mm,DATEADD(mm,b.Month, -1)) as 'Month', 
a.Loc, 
SUM(ISNULL(CASE WHEN A.[Type] = 'NEW' AND A.Leg = 1 THEN 1 ELSE 0 END, 0)) - SUM(ISNULL(CASE WHEN a.[Type] = 'CAN' AND a.Leg = 1 THEN 1 ELSE 0 END, 0)) AS 'Total Bookings',
SUM(ISNULL(CASE WHEN A.[Type] = 'NEW' THEN (a.Revenue * e.To_USD_Rate) END, 0)) - SUM(ISNULL(CASE WHEN a.[Type] = 'CAN' THEN (a.Revenue * e.To_USD_Rate) END, 0)) AS 'Revenue in USD',
SUM(a.Leg) AS Leg_sum
FROM Bookings a
LEFT OUTER JOIN Calendar b on b.Date_ID = a.Arrival_Date
LEFT OUTER JOIN Exchange_Rates e on e.Currency = a.Currency
WHERE a.Loc = 'RYH'
AND b.Month IN (MONTH(b.Year), MONTH(b.Year)+1, MONTH(b.Year)+2)
AND b.Year IN (Year(GETDATE()), Year(GETDATE())-1)
GROUP BY b.year, DateName(mm,DATEADD(mm,b.Month, -1)), a.Loc ) temp
Order BY [Year], [Month]
Random Solutions  
 
programming4us programming4us