两个select语句的Sum结果

时间:2011-12-27 18:00:13

标签: sql sql-server sql-server-2008 tsql

我们的员工每周都会获得佣金,由于奖金结构,我必须计算两个单独的工资周,然后将两者加在一起。

我有以下SQL语句,它获得两个单独的周结果

    SELECT  PerceptionistID, SSNLastFour, CommissionPay,
        PTOPay, HolidayPay, Overtime, TotalPay
    FROM [dbo].fnCalculateCommissionForWeekOf(@MondayOfCurrentWeek)

    UNION

    -- 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)

这可以获得我需要的数据,但我想将两个结果合并到一个具有相同列的表中,但将一些列添加到一起(CommissionPay,PTOPay,HolidayPay,Overtime,TotalPay)。做这个的最好方式是什么?我正在使用SQL Server 2008 R2。

3 个答案:

答案 0 :(得分:13)

试试这个

SELECT PerceptionistID, SSNLastFour, SUM(CommissionPay) CommissionPay,
        SUM(PTOPay) PTOPay, SUM(HolidayPay) HolidayPay, SUM(Overtime) Overtime, SUM(TotalPay) TotalPay
FROM
(
    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)
) t
GROUP BY PerceptionistID, SSNLastFour

答案 1 :(得分:1)

使您的查询成为子查询,并在“超级查询”级别进行分组:

SELECT PerceptionistID, SSNLastFour, sum(CommissionPay), ...
FROM 
(
SELECT  PerceptionistID, SSNLastFour, CommissionPay,
    PTOPay, HolidayPay, Overtime, TotalPay
FROM [dbo].fnCalculateCommissionForWeekOf(@MondayOfCurrentWeek)

UNION

-- 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)
) AS X
GROUP BY PerceptionistID, SSNLastFour

答案 2 :(得分:0)

如何修改[dbo] .fnCalculateCommissionForWeekOf或创建一个采用开始和结束日期的新函数。通过这种方式,您可以使用相同的功能和相同的逻辑来运行任何日期,包括过去一周,两周,一个月,一年等。