我有以下表格 -
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))
......它就无效了。
从概念上讲,我被封锁了。有人可以指导我吗?提前谢谢。
答案 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