Sum results from two select statements Sum results from two select statements sql sql

Sum results from two select statements


Try this

SELECT PerceptionistID, SSNLastFour, SUM(CommissionPay) CommissionPay,        SUM(PTOPay) PTOPay, SUM(HolidayPay) HolidayPay, SUM(Overtime) Overtime, SUM(TotalPay) TotalPayFROM(    SELECT  PerceptionistID, SSNLastFour, CommissionPay,        PTOPay, HolidayPay, Overtime, TotalPay    FROM [dbo].fnCalculateCommissionForWeekOf(@MondayOfCurrentWeek)    UNION ALL    -- Need to get the following week's data and sum the two together    SELECT  PerceptionistID, SSNLastFour, CommissionPay,        PTOPay, HolidayPay, Overtime, TotalPay    FROM [dbo].fnCalculateCommissionForWeekOf(@MondayOfFollowingWeek)) tGROUP BY PerceptionistID, SSNLastFour


Make your query a subquery, and group at the 'superquery' level:

SELECT PerceptionistID, SSNLastFour, sum(CommissionPay), ...FROM (SELECT  PerceptionistID, SSNLastFour, CommissionPay,    PTOPay, HolidayPay, Overtime, TotalPayFROM [dbo].fnCalculateCommissionForWeekOf(@MondayOfCurrentWeek)UNION-- Need to get the following week's data and sum the two togetherSELECT  PerceptionistID, SSNLastFour, CommissionPay,    PTOPay, HolidayPay, Overtime, TotalPayFROM [dbo].fnCalculateCommissionForWeekOf(@MondayOfFollowingWeek)) AS XGROUP BY PerceptionistID, SSNLastFour


How about modifying [dbo].fnCalculateCommissionForWeekOf or creating a new function that takes a start and end date. This way you can use the same function, and same logic, to run against any span of dates, including the past week, 2 weeks, month, year etc.