根据table2选择table1中列的总和?

时间:2017-09-21 15:32:22

标签: mysql sql database

我有两个表,员工和交易,如下所示:

 employees: 
 EmployeeID
 firstname
 lastname

 transactions: 
 TransactionID
 employeeID
 amount

我如何获得名为'John'的所有员工的总额'?谢谢!

 Select sum(amount) 
 from transactions 
 where employeeID = (everyone with first name John)

5 个答案:

答案 0 :(得分:3)

您只需要执行JOIN

Select  Sum(T.Amount)
From    Transactions    T
Join    Employees       E   On  E.EmployeeId = T.EmployeeId
Where   E.FirstName = 'John'

答案 1 :(得分:3)

尝试:

Select sum(amount)
from transactions
where employeeID 
   in (Select employeeID from employees 
       where firstname ='firstname');

thx;)

答案 2 :(得分:3)

你快到了。尝试:

SELECT SUM(amount) 
FROM transactions t
INNER JOIN employees e
    ON t.employeeID = e.employeeID
WHERE e.firstName = 'John'

或者,这也适用

SELECT SUM(amount) 
FROM transactions t
WHERE t.employeeId IN (
    SELECT employeeID
    FROM employees e
    WHERE e.firstName = 'John'
    )

答案 3 :(得分:3)

INNER JOIN应该可以解决问题。看看下面提供的查询:

SELECT SUM(T.amount) FROM
Transactions T INNER JOIN Employees E
ON T.EmployeeID = E.EmployeeID
WHERE E.FirstName = 'John'

答案 4 :(得分:2)

这是我的猜测。您必须将两个表连接在一起,然后过滤所需的数据。

SELECT     SUM(tr.amount)
FROM       Employees emp
INNER JOIN transactions tr ON emp.employeeId = tr.EmployeeId
WHERE      emp.FirstName = 'John'