Reputation: 23
Employee
empId
empName
empStoreNum
Invoice
invNo
invAmount
empId
I have two tables above Employee and Invoice. I would like to setup a query to retrieve employee names, employee store numbers, and the total sales for each employee. I have issue a query below and it works but I was not able to retrieve employee store number.
SELECT Emp.empName, Sum(Inv.invAmount) AS totalSales
FROM Invoice AS Inv INNER JOIN Employee AS Emp ON Inv.empId = Emp.empId
GROUP BY Emp.empName
If I add Emp.empStoreNum to the SELECT I get the following error: “You tried to execute a query that does not include the specified expression ‘empStoreNum’ as part of an aggregate function.” How can modify the query to get employee store number also?
Upvotes: 1
Views: 1449
Reputation: 11474
Try adding empStoreNum to GROUP BY
SELECT Emp.empName, Emp.empStoreNum, Sum(Inv.invAmount) AS totalSales
FROM Invoice AS Inv INNER JOIN Employee AS Emp ON Inv.empId = Emp.empId
GROUP BY Emp.empName, Emp.empStoreNum
Upvotes: 2
Reputation: 755064
All non-aggregate columns in the select-list must be listed in the GROUP BY clause (unless you're using MySQL, which plays by a very different set of rules, or unless you are using a sufficiently recent version of PostgreSQL, which is able to deduce functional dependencies).
SELECT Emp.empName, Emp.empStoreNum, Sum(Inv.invAmount) AS totalSales
FROM Invoice AS Inv INNER JOIN Employee AS Emp ON Inv.empId = Emp.empId
GROUP BY Emp.empName, Emp.empStoreNum
Upvotes: 2