我有一张叫做员工的桌子:
CREATE TABLE Employees
(
Id INT NOT NULL PRIMARY KEY IDENTITY(1,1),
FullName NOT NULL NVARCHAR(100)
)
我有另一个名为Sales
的表CREATE TABLE SALES
(
Id INT NOT NULL PRIMARY KEY IDENTITY(1,1),
CustomerId INT NOT NULL FOREGIN KEY REFERENCES SOMETABLE(id),
AMOUNT DECIMAL(15,4) NOT NULL,
EmployeeId INT NOT NULL FOREGIN KEY REFERENCES Employees(Id),
SaleDate DATETIME2 NOT NULL
)
另一个名为Calls的表
CREATE TABLE Calls
(
Id INT NOT NULL PRIMARY KEY IDENTITY(1,1),
Date DATETIME2 NOT NULL,
EmployeeId INT NOT NULL FOREGIN KEY REFERENCES Employees(Id)
)
我需要运行一个查询,告诉我员工卖东西的最后日期,以及自那次销售以来他们怎么称呼他们。
我试过的是
SELECT
LAST_DATE_SOLD = MAX(Sales.Date)
, Employees.FullName
, Count(Calls.*)
FROM Employees
LEFT OUTER JOIN SALES ON Sales.EmployeeId = Employees.Id
LEFT OUTER JOIN Calls On Calls.EmployeeId = Employees.Id
GROUP BY Employees.FullName
如果有人可以帮助解决这个问题,我没有得到正确的价值。
答案 0 :(得分:2)
有很多方法可以给这只猫上皮。这是其中之一。请注意,这是加入呼叫,其中日期大于上次销售日期,因此它只返回这些呼叫。
with SortedResults as
(
select *
, ROW_NUMBER() over(partition by e.EmployeeID order by s.SalesDate desc) as RowNum
from Sales s
join Employee e on e.EmployeedID = s.Id
)
select s.SalesDate
, s.FullName
, count(*)
from SortedResults s
join Calls c on c.EmployeedId = s.EmployeeId and c.Date > s.SaleDate
where s.RowNum = 1
group by s.SalesDate, s.FullName
答案 1 :(得分:0)
我认为Max(Sales.Date)
不正确。试试这个
SELECT
LAST_DATE_SOLD = MAX(SaleDate)
, Employees.FullName
, Count(Calls.*)
FROM Employees
LEFT OUTER JOIN SALES ON Sales.EmployeeId = Employees.Id
LEFT OUTER JOIN Calls On Calls.EmployeeId = Employees.Id
GROUP BY Employees.FullName
答案 2 :(得分:0)
你可以试试这个:
WITH qry1
AS ( SELECT EmployeeId ,
MAX(SaleDate) LatestSaleDate
FROM dbo.SALES
GROUP BY EmployeeId
)
SELECT qry1.EmployeeId ,
LatestSaleDate ,
SUM(CASE WHEN c.date > LatestSaleDate THEN 1
ELSE 0
END) NumberOfCalls
FROM qry1
LEFT JOIN Calls c ON qry1.EmployeeId = c.EmployeeId
GROUP BY qry1.EmployeeId, LatestSaleDate
答案 3 :(得分:0)
SELECT e.fullname,
c.date,
COUNT(c.id)
FROM calls c
INNER JOIN employees e
ON c.employee_id = e.employee_id
WHERE date >= (SELECT MAX(saledate)
FROM sales
WHERE employee_id = c.employee_id
)
GROUP BY e.fullname,
c.date