我的数据库中有以下四个表:
EMPLOYEE
PK: employeeID;
FK: empBranch references BRANCH;
FK: empSupervisor references EMPLOYEE
BRANCH
PK: branchNumber
FK: branchManager references EMPLOYEE
CUSTOMER
PK: customerID
订单
PK: orderNumber
FK: customerID references CUSTOMER;
FK: salesPerson references EMPLOYEE
现在我需要列出这两件事:
仅销售给与销售人员分支所在城市位于同一城市的客户的员工ID和销售人员姓名。
已销售给与销售人员分支所在城市位于同一城市的每位客户的员工ID和销售人员姓名。
请帮我回答两个问题
答案 0 :(得分:1)
仅销售给与销售人员分支所在城市位于同一城市的客户的Employee_ID和销售人员姓名。
SELECT DISTINCT
e.employeeid,
e.emplname || e.empfname AS salesperson_name
FROM
orders o
INNER JOIN customer c ON o.customerid = c.customerid
INNER JOIN branch b ON o.salesperson = b.branchmanager
INNER JOIN employee e ON o.salesperson = e.employeeid
WHERE
c.custcity = b.branchcity -- salesperson's branch located in the same city as customer
答案 1 :(得分:1)
由于您没有指定特定的RDBMS,因此这是为SQL Server编写的。
仅销售给与销售人员分支所在城市位于同一城市的客户的Employee_ID和销售人员姓名。
null
已销售给与销售人员分支所在城市位于同一城市的每位客户的员工ID和销售人员姓名。
有多种方法可以获得每个城市的计数,但我使用了CTE。
SELECT
e.EmployeeID,
e.Empfname + ' ' + e.Emplname Name
FROM Orders o
JOIN customer c
ON o.CustomerID = c.CustomerId
JOIN Employee e
ON o.SalesPerson = e.Employeeid
JOIN Branch b
ON e.EMPBRANCH = b.BranchManager
GROUP BY e.Employeeid, e.EMPFNAME + ' ' + e.EMPLNAME
HAVING COUNT(CASE WHEN c.custCity <> b.BranchCity THEN 1 END) = 0 -- no sales outside of the employee's city