之前我已经完成了这个查询,但由于某种原因,我总是需要挖掘答案。有人可以为我解释解决方案,这样我终于可以“得到它”! (谢谢!)
Table#1 Employees (employeeID, username)
Table#2 Sales (saleID, employeeID, amount)
问题:列出所有员工,以及他们的销售总数#(计数)。
答案 0 :(得分:2)
您需要选择所有员工,并计算每个员工的销售额。因为您需要列表中的所有员工,所以您可以从Employees表中进行选择,并左键连接到sales表,或者对sales表执行子查询。这样做可以使您的员工在结果中的销售额为零。在联接的情况下,您必须按员工分组并计算销售表中的记录。对于子查询,没有group by,因为您的基本查询每个员工只返回1行。
select Employees.EmployeeID,
Employees.UserName,
CountOfSales = COUNT(SaleID)
from Employees LEFT JOIN
Sales ON Employees.EmployeeID = Sales.EmployeeID
group by Employees.EmployeeID,
Employees.UserName
/*
EmployeeID UserName CountOfSales
----------- ---------- ------------
2 bill 1
3 larry 0
1 scott 2
Warning: Null value is eliminated by an aggregate or other SET operation.
*/
- 或 -
select E.*,
CountOfSales = (select count(*)
from sales
where EmployeeID = E.EmployeeID)
from Employees E
/*
employeeID username CountOfSales
----------- ---------- ------------
1 scott 2
2 bill 1
3 larry 0
*/
每个查询的结果都基于以下示例数据......
create table Employees (employeeID int , username varchar(10))
create table Sales (saleID int , employeeID int , amount smallmoney)
go
insert Employees values (1, 'steve'), (2, 'bill'), (3, 'larry')
insert Sales values (1, 1, 23), (2,1,33), (3,2,0)
go
答案 1 :(得分:2)
select
e.employeeID
, e.username
, count(s.saleID) as'sales count'
, sum(s.amount) as 'sales $ total'
from
employees e
left outer join
sales s
on
s.employeeID = e.employeeID
group by
e.employeeID
, e.username
答案 2 :(得分:1)
你说你想要问题标题中的总和但是然后说你想要体内的#(计数)。
如果你想要总和,那么在SQL中使用SUM函数。
select Employees.EmployeeID, TotalSales = SUM(amount)
from Employees LEFT JOIN Sales ON Employees.EmployeeID = Sales.EmployeeID
答案 3 :(得分:1)
假设只能由一名员工进行一次销售,这不是很简单吗?
选择Employees.username,count(Sales.saleID)
从员工左侧加入Employees上的销售额.employeeID = Sales.employeeID
按Employees.username分组
答案 4 :(得分:0)
select emp.username
,isnull((select count(*)
from sales
where sales.employeeid = emp.employeeid),0) as [number of sales]
from employees emp