将从其他表的列到表的另一列的所有值总计

时间:2017-03-22 06:30:11

标签: sql-server

我有数据表" tblTardiness"使用每列的值" EmployeeName"和" TardinessPay"。

EmployeeName TardinessPay

杰伊53.42 杰伊30.20 杰伊20.03 保罗53.42 保罗53.42 迈克20.03 迈克20.03 迈克53.42 迈克20.03

另一个数据是" tblSalary"列上的值为#34; EmployeeName" " TardinessPay"

上的空值或空值

EmployeeName TardinessPay

Jay NULL Paul NULL Mike NULL

如何从" tblTardiness"计算每个EmployeeName的总值为TardinessPay?并自动保存到" tblSalary"。 看看下面的情况如何

EmployeeName TardinessPay

杰伊103.65 保罗106.84 迈克113.51

到目前为止,我通过过滤每个员工只使用了Where子句。但我需要所有员工。请再帮我一次。谢谢!

3 个答案:

答案 0 :(得分:3)

你可以试试这个

select sum(TardinessPay) from tbltardiness group by EmployeeName;

答案 1 :(得分:2)

试试这个:

 select * from tblTardiness

EmployeeName TardinessPay

杰伊53.4200 杰伊30.2000 周杰伦20.0300

 select * from tblSalary

EmployeeName TardinessPay

Jay NULL

Update a set a.TardinessPay = b.pay from tblSalary a inner join (select EmployeeName,sum(TardinessPay) pay from tblTardiness group by EmployeeName) b on a.EmployeeName = b.EmployeeName


select * from tblSalary

EmployeeName TardinessPay

杰伊103.6500

答案 2 :(得分:1)

您可以按每个员工分组,并将他们的迟到费用相加。请检查以下查询,并希望它符合您的要求:

DECLARE @tblTardiness TABLE (EMPLOYEENAME VARCHAR(100), TARDINESSPAY NUMERIC(10,2))
DECLARE @tblSalary TABLE (EMPLOYEENAME VARCHAR(100), TARDINESSPAY NUMERIC(10,2))

INSERT INTO @tblTardiness VALUES('JAY',53.42),('JAY',30.20),('JAY',20.03),('PAUL',53.42),('PAUL',53.42),('MIKE',20.03),('MIKE',53.42),('MIKE',20.03),('MIKE',20.03)

INSERT INTO @tblSalary
SELECT EMPLOYEENAME, SUM(TARDINESSPAY)
FROM @tblTardiness
GROUP BY EMPLOYEENAME

SELECT * FROM @tblSalary ORDER BY EMPLOYEENAME