sqlsql-servernorthwind

Create a query that displays the employees with no sale in the last 3 days from a date to customers who are from "USA". northwind database


I want to get the employees with no sale in the last 3 days before 1997-01-25 to customers who are from "USA".

Orders table

OrderID CustomerName    EmployeeId  Orderdate
10248   C1               1             1997-01-25 00:00:00:000
10249   C2               3             1997-0-24 00:00:00:000
10250   C3               2             1997-01-23 00:00:00:000
10251   c4               5             1997-01-22 00:00:00:000
10251   c5               4             1997-01-23 00:00:00:000

Employees

EmployeeID  Emp_name
1            E1
2            E2  and so on till e5

Customers

CustomerID   Country
C1            USA
C2            UK
C3            Brazil
C4            UK 
C5            USA

Desired result

EmployeeID
2
3
5

Query tried

select EmployeeID
from Employees e1
where employeeid not in
(
    select o.EmployeeID
    from orders o
    full join customers c on o.CustomerID=c.CustomerID
    where c.Country = 'USA' 
    and o.RequiredDate >= dateadd(day,-3, '1997-01-25')
)

However I am getting blank result, as in no rows. can anyone pls help. (this is just a specimen): data from northwind database. I have just created sample data in case someone does not have northwind database


Solution

  • Based entirely on the table data you "provided", the problem is that you are looking for an Employee id of integer and your sub-query is returning a list of employee names. So if you modify it as such you will get the correct answer:

    CREATE TABLE #Orders (OrderID int, CustomerName varchar(20), EmployeeName varchar(20), Orderdate datetime)
    INSERT INTO #Orders VALUES
    (10248, 'C1', 'E1', '1997-01-25 00:00:00:000'),
    (10249, 'C2', 'E3', '1997-01-24 00:00:00:000'),
    (10250, 'C3', 'E2', '1997-01-23 00:00:00:000'),
    (10251, 'c4', 'e5', '1997-01-22 00:00:00:000'),
    (10251, 'c5', 'e4', '1997-01-23 00:00:00:000')
    
    CREATE TABLE #Employees (EmployeeID int, Emp_name varchar(10))
    INSERT INTO #Employees VALUES
    (1, 'E1'),
    (2, 'E2'),
    (3, 'E3'),
    (4, 'E4'),
    (5, 'E5')
    
    CREATE TABLE #Customers (CustomerID varchar(10), Country varchar(20))
    INSERT INTO #Customers VALUES
    ('C1', 'USA'),
    ('C2', 'UK'),
    ('C3', 'Brazil'),
    ('C4', 'UK' ),
    ('C5', 'USA')
    
    select Emp_name
    from #Employees e1
    where Emp_name not in
    (
        select o.EmployeeName
        from #orders o
        inner join #customers c on o.CustomerName = c.CustomerID
        where c.Country = 'USA' 
        and o.Orderdate >= dateadd(day,-3, '1997-01-25')
    )