Avatar of Rick0124
Rick0124
Flag for United States of America asked on

Retrieve records that are not in specified timeframe

Hello, Experts!

I am still a newbie in SQL Server and I need your help.  I have a table with the following structure:

Container_no, nvarchar(12)
Line, nchar(10)
Activity_Date, datetime
Activity, nvarchar(50)

Each container could have 50 or more activity records with different dates.  I need to be able to retrieve the container numbers that do not have activity between the dates 01/01/2011 and 12/31/2011.  I tried the following script but doesn't work:

SELECT DISTINCT Container_no
  FROM Reefer_Movements
  WHERE NOT EXISTS (SELECT Container_no, Activity_Date
  FROM Reefer_Movements
  WHERE Activity_Date BETWEEN '01/01/2011' AND '12/31/2011')
  ORDER BY Container_no

Any help would be very much appreciated.

Thanks!
Microsoft SQL Server.NET Programming

Avatar of undefined
Last Comment
Rick0124

8/22/2022 - Mon
Andy Marshall

How about

SELECT DISTINCT Container_no
FROM Reefer_Movements
WHERE Activity Date <  '01/01/2011' AND Activity Date > '12/31/2011'
ORDER BY Container_no
HainKurt

try

SELECT DISTINCT container_no
FROM   reefer_movements
WHERE  activity_date NOT BETWEEN '01/01/2011' AND '12/31/2011'
ORDER  BY container_no
Rick0124

ASKER
Thanks, Experts!
I tried both scripts but the first one still gets records that have activity for the given dates, while the second one doesn't return any records.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER CERTIFIED SOLUTION
Rick0124

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
deighton

SELECT DISTINCT Container_no
  FROM Reefer_Movements
  WHERE NOT EXISTS (SELECT 0
  FROM Reefer_Movements RM
  WHERE RM.Activity_Date BETWEEN '01/01/2011' AND '12/31/2011' AND RM.Container_no = Reefer_Movements.Container_no)
  ORDER BY Container_no
Rick0124

ASKER
I checked random containers to see if their activity does not fall between the specified dates and so far, they don't.  Out of a total of more than 110k distinct containers, the query result gave me a little less than 6k distinct containers.