如何从一个到多个关系表中获得总和值?

时间:2015-12-08 05:03:43

标签: mysql database

我有两个表tasktask_detail,有一对多的关系。表格如下图所示。

我只想要task_detail中的所有任务数据和金额总和,其中task_id等于任务的id。我已经尝试了一些查询,但似乎没有人能为我工作。

SELECT t.*, td.amount AS amount FROM task AS t 
LEFT JOIN task_detail AS td ON t.emp_id=td.emp_id  WHERE t.emp_id=52

有没有办法解决这个问题?

enter image description here

3 个答案:

答案 0 :(得分:4)

您想为52名员工的每项任务获得金额的总和吗?然后你可以使用下面的查询来完成它。如果没有,请详细说明。

SELECT task_id, SUM(amount)
FROM task_detail
WHERE emp_id = 52
GROUP BY task_id

如果您想获取任务的另一列,您可以使用:

SELECT t.*, td.amt
FROM task AS t 
    INNER JOIN (
        SELECT task_id, SUM(amount) AS amt
        FROM task_detail
        WHERE emp_id = 52
        GROUP BY task_id
    ) AS td ON t.task_id = td.task_id
WHERE t.emp_id = 52

答案 1 :(得分:0)

使用SUM或Group by

SELECT SUM(td.amount) AS amount
FROM task AS t
LEFT JOIN task_detail AS td ON t.emp_id = td.emp_id
WHERE t.emp_id = 52
Group by task_id

答案 2 :(得分:0)

使用聚合函数,group by子句是强制性的,如前所述,首先回答它不会给出和

          select t1.firstname, sum(t2.amount) as 'total', t1.taskID  
          from tasks t1 join task_Details t2 
          on t1.UserID = t2.UserId
          where t1.UserID = 3
          group by t1.firstname, t1.taskID