Question

I might have a really simple question, but it doesn't seem i can find the solution yet. Basically, i have to write a SQL-Server function, based on Northwind DB. It has to:

Take 2 dates as arguments and display, without repetition these Customer's data ID | Name | City | Address , for those customers where the total purchase he had made from at least one Employee , is greater than the average sale made by this Employee between the two dates.

So the main steps should be:
1. Retrieve the total purchase made from a Customer from each Employee. I know how to get the total purchase from each Company:

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

But how can i get those made from each employee?

2.Confront this with the average sales of this Employee between the given dates. I can get the average for each employee:

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

Note that i'm only pasting the query part, but here, the Employee should depend on the first query (probably this should be put inside a subquery)

Everything should be put inside a single function (it should not be split in two). The Northwind DB diagram is: Northwind Diagram . Please help!

Was it helpful?

Solution

Hope I got the logic right:

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')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top