在mysql中按聚合SQL输出分组执行聚合

时间:2017-08-16 13:28:21

标签: mysql sql

我有以下表格 -

Employee  - 
Employee_Id     Name        Limit_Amt
1               Sachin      3000
2               Mahi        2500

Employee_Wage  - 
Employee_Id     Amount      Pay_Date
1               200         2017-01-01
1               250         2017-02-01
1               300         2017-03-01
2               350         2017-01-01
2               400         2017-02-01
2               300         2017-03-01

现在找出查询以下个别员工的剩余限额正常 -

SELECT e.Limit_Amt - SUM(Amount) AS 'Remaining Limit' 
FROM Employee e, Employee_Wage ew 
WHERE e.Employee_Id = ew.Employee_Id 
GROUP BY e.Employee_Id, e.Limit_Amt

它将输出显示为 -

Remaining Limit
2250
1450

但是,我希望进一步计算剩余限制总数(即得出3700),然后如果我申请SUM(e.Limit_Amt - SUM(Amount)) ......它就无效了。

从概念上讲,我被封锁了。有人可以指导我吗?提前谢谢。

2 个答案:

答案 0 :(得分:1)

您可以使用子查询:

SELECT  SUM(remaining)
FROM    (
        SELECT  e.Limit_Amt - SUM(Amount) AS remaining
        FROM    Employee e
        JOIN    Employee_Wage ew 
        ON      e.Employee_Id = ew.Employee_Id
        GROUP BY
                e.Employee_Id
        ,       e.Limit_Amt
        ) sub

from a join b on a.id = b.id语法比SQL92的from a, b where a.id = b.id更清晰。

答案 1 :(得分:0)

select e.Name,e.Limit_Amt,sum(cast(w.Amount as int)) 'sum',
e.Limit_Amt-sum(cast(w.Amount as int)) 'Remaining'
from Employee e join Employee_Wage w
on e.Employee_Id=w.Employee_Id
group by e.Name,e.Limit_Amt