我可能有一个非常简单的问题,但似乎我无法找到解决方案。基本上,我必须编写一个基于Northwind DB的SQL-Server函数。它必须:
将2个日期作为参数并显示,而不是重复这些客户数据ID | Name | City | Address
,对于那些客户,其中至少购买了一次 员工,大于此员工在两个日期之间的平均销售额。
所以主要步骤应该是:
1.从每个员工中检索客户的总购买量。我知道如何从每个公司获得总购买量:
SELECT
Customers.CompanyName, SUM(UnitPrice*Quantity)
FROM Orders inner join [Order Details]
ON Orders.OrderID=[Order Details].OrderID INNER JOIN
Customers ON Orders.CustomerID=Customers.CustomerID
GROUP BY Customers.CompanyName
但我如何从每位员工那里获得这些?
2.在给定日期之间与此员工的平均销售额对应。我可以得到每个员工的平均值:
SELECT FirstName+' '+LastName, AVG(UnitPrice*Quantity)
FROM Orders inner join [Order Details]
ON Orders.OrderID=[Order Details].OrderID
INNER JOIN Employees
ON Orders.EmployeeID=Employees.EmployeeID
WHERE OrderDate BETWEEN @dt1 and @dt2
GROUP BY FirstName+' '+LastName
请注意,我只粘贴查询部分,但在这里,Employee应该依赖于第一个查询(可能这应该放在子查询中)
所有东西都应该放在一个单独的功能中(不应该分成两部分)。 Northwind DB图是:Northwind Diagram。请帮忙!
答案 0 :(得分:2)
希望我的逻辑是正确的:
create function x (@from datetime, @to datetime)
returns table
as
return (
with cust as (
select o.customerid, o.employeeid, sum(unitprice*quantity) as cust_purchase
from orders o
inner join [order details] d on o.orderid=d.orderid
where o.orderdate between @from and @to
group by o.customerid, o.employeeid
),
emp as (
select o.employeeid, avg(unitprice*quantity) as emp_sale
from orders o
inner join [order details] d on o.orderid=d.orderid
where o.orderdate between @from and @to
group by o.employeeid
)
select c.customerid, c.companyname, c.city, c.address
from cust
inner join emp on cust.employeeid = emp.employeeid
and cust.cust_purchase > emp.emp_sale
inner join customers c on cust.customerid = c.customerid
)
go
select * from x ('19980401', '19980430')