sql – 来自两个select语句的Sum结果

前端之家收集整理的这篇文章主要介绍了sql – 来自两个select语句的Sum结果前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我们的员工每周都会获得佣金,由于奖金结构,我必须计算两个单独的工资周,然后将两者加在一起.

我有以下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,TotalPay
    FROM [dbo].fnCalculateCommissionForWeekOf(@MondayOfFollowingWeek)

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

解决方法

试试这个
SELECT PerceptionistID,SUM(CommissionPay) CommissionPay,SUM(PTOPay) PTOPay,SUM(HolidayPay) HolidayPay,SUM(Overtime) Overtime,SUM(TotalPay) TotalPay
FROM
(
    SELECT  PerceptionistID,TotalPay
    FROM [dbo].fnCalculateCommissionForWeekOf(@MondayOfCurrentWeek)

    UNION ALL

    -- Need to get the following week's data and sum the two together
    SELECT  PerceptionistID,TotalPay
    FROM [dbo].fnCalculateCommissionForWeekOf(@MondayOfFollowingWeek)
) t
GROUP BY PerceptionistID,SSNLastFour
原文链接:https://www.f2er.com/mssql/78795.html

猜你在找的MsSQL相关文章