查询以汇总来自MySQL中不同表的不同列

时间:2019-10-16 07:13:54

标签: mysql sum left-join inner-join

我有三个表,我试图将它们连接起来,并从两个表中获取它们的总和,然后从表中添加两个和。

在这里,我有一个SQL Fiddle用于查询的结构:http://www.sqlfiddle.com/#!9/cb00bc/3/0

我想要这样的输出:

emp_id   firstname  middlename  lastname    name_ext    SUM(amount_paid)    SUM(salary_paid) SUM(total) 

  1        test        test        test        test          300                  500             800

2 个答案:

答案 0 :(得分:1)

无需子查询,只需SUM个值和GROUP BY tbl_user

SELECT DISTINCT tbl_user.firstname,
tbl_user.middlename,
tbl_user.lastname,
tbl_user.name_ext,
sum(coalesce(tbl_overtime.amount_paid,0)),
sum(coalesce(tbl_salary.salary_paid,0)),
sum(coalesce(tbl_salary.salary_paid,0)+coalesce(tbl_overtime.amount_paid,0))
FROM tbl_user
INNER JOIN tbl_salary ON tbl_user.employee_id = tbl_salary.employee_id
LEFT JOIN tbl_overtime ON tbl_overtime.employee_id = tbl_salary.employee_id
GROUP BY tbl_user.firstname,
tbl_user.middlename,
tbl_user.lastname,
tbl_user.name_ext

答案 1 :(得分:1)

这是您的查询。您的表格将加入一个具有按员工ID进行合计分组的子查询。

SELECT DISTINCT tbl_user.firstname,
  tbl_user.middlename,
  tbl_user.lastname,
  tbl_user.name_ext,
  t3.amount_paid,
  t3.salary_paid,
  t3.total
FROM tbl_user
INNER JOIN tbl_salary ON tbl_user.employee_id = tbl_salary.employee_id
LEFT JOIN tbl_overtime ON tbl_overtime.employee_id = tbl_salary.employee_id
left join
  (select t1.employee_id
       , SUM(coalesce(t2.amount_paid, 0)) as amount_paid
       , SUM(coalesce(t1.salary_paid, 0)) as salary_paid
       , SUM(coalesce(t2.amount_paid, 0))  + SUM(coalesce(t1.salary_paid, 0)) as total
     from tbl_salary t1
     left join tbl_overtime t2 on t2.employee_id = t1.employee_id
     group by t1.employee_id) as t3 on t3.employee_id = tbl_user.employee_id