我一直在尝试进行以下练习,即使用SQL创建查询,"查找一周内拥有3个以上客户的推销员数量。显示员工ID,员工姓名,客户ID,客户名称以及销售员会见的客户数量。"
实体和相关领域是:
Staff: [Staff_ID (PK), Staff_Name, ...]
Clients: [Client_ID (PK), Client_Name, Staff_ID (FK), ...]
Sales: [Sale_ID (PK), Client_ID (FK), Staff_ID (FK), Date_of_Sale, ...]
(All data are strings except Date_of_Sale, which is in DATE format)
我试图通过以下方式实现这一目标:
SELECT t.Staff_ID, t.Staff_Name, COUNT(s.Client_ID),
COUNT(c.Client_Name), DATEPART(wk, s.Date_of_Sale) as Week
FROM Clients c, Staff t, Sales s
GROUP BY DATEPART(wk, s.Date_of_Sale), t.Staff_ID, t.Staff_Name
HAVING COUNT(DATEPART(wk, s.Date_of_Sale)) > 3
我知道它不正确,但我不知道如何修复它,因为我在sql中非常不熟练。我想了解如何做到这一点,我可以(在有限的程度上)通过逆向工程来实现。更好的是,如果有人要为我解释,我会非常感激,谢谢你。
答案 0 :(得分:0)
我们走了
WITH CTE AS (
SELECT *, DATEPART(wk, s.Date_of_Sale) as SALES_WEEK
FROM Clients c
INNER JOIN Sales s ON c.Client_ID = s.CLIENT_ID
INNER JOIN Staff t ON t.STAFF_ID = s.STAFF_ID
)
SELECT SALES_WEEK, Staff_ID, Staff_Name, COUNT(1) AS NO_OF_SALES
FROM CTE
GROUP BY SALES_WEEK, Staff_ID, Staff_Name
HAVING COUNT(1) > 3
希望这可以按预期工作
答案 1 :(得分:0)
推销员遇到的客户数与推销员的销售数之间存在很大差异。主要是,是否计算对同一客户的重复访问次数。前者说不,后者说是,因为客户的数量没有变化,但销售数量却有所不同。
-- Get list of clients with sales greater than 3 in a week
WITH SalesCount AS (
SELECT Client_ID AS 'Client', DATEPART(wk, Date_of_Sale) AS 'week',
COUNT(Staff_ID) AS 'Sales_Count'
FROM Sales
GROUP BY DATEPART(wk, Date_of_Sale), Client_ID
HAVING COUNT(Staff_ID) > 3 ),
-- Shorten the list to unique entries and add the StaffID
ClientList AS (
SELECT DISTINCT sc.Client, c.Staff_ID
FROM SalesCount AS sc
INNER JOIN Clients AS c ON sc.Client = c.Client_ID) ,
-- Create a count of clients visited
ClientCount AS (
SELECT COUNT(l.Client) AS visitors, l.Staff_ID
FROM ClientList AS l
GROUP BY l.Staff_ID)
SELECT cc.visitors, cc.Staff_ID, l.Client, t.Staff_Name
FROM ClientCount AS cc
INNER JOIN ClientList AS l ON cc.Staff_ID = l.Staff_ID
INNER JOIN Staff AS t ON t.Staff_ID = l.Staff_ID
INNER JOIN Clients AS c ON l.Client = c.Client_ID