tags:

views:

299

answers:

5

I have a SQL table with two columns Date and User and contains the following rows:

    **Date        User**
    2009-02-20  Danny
    2009-02-20  Matthew
    2009-02-15  William
    2009-02-15  Abner
    2009-12-14  Joseph
    1900-01-01  Adam
    1900-01-01  Eve

Given a date, how should I write my WHERE clause to return a list of users for that date, or if no users users were found for that date, return a list of users for the next earlier date. For example, if the given date is '2009-02-19', the users list returned should be William and Abner.

A: 
SELECT * 
FROM [MyTable] t
INNER JOIN
   ( 
      SELECT TOP 1 [Date]
      FROM [MyTable]
      WHERE [Date] >= @TargetDate
      ORDER BY [Date]
   ) d ON t.[Date] = d.[Date]
Joel Coehoorn
+6  A: 
SELECT User
FROM MyTable
WHERE MyDate = (SELECT MAX(MyDate) FROM MyTable WHERE MyDate <= '2009-02-19')
cletus
you have an extra )... it should be WHERE Date = (SELECT MAX(MyDate) FROM MyTable WHERE MyDate <= '2009-02-19')
Lawrence Barsanti
+1 just because its such a Brilliant answer. :P
AnthonyWJones
+5  A: 
SELECT [User] FROM myTable WHERE Date =
  (SELECT Max(Date) FROM myTable WHERE Date <= '2009-02-19')
AnthonyWJones
How's this get voted up when I wrote the exact same thing earlier? *scratches head*
cletus
Like you need the rep cletus ;)
Pauk
I'm reminded of a Simpsons quote where Homer says, "Lisa, a guy who's got lots of ivory is less likely to hurt Stampy than a guy whose ivory supplies are low."
cletus
@cletus: it wasn't exactly the same originally, yours had a Select * in there briefly ;) Still you got the answer tick and now more votes.
AnthonyWJones
A: 

Something like this:

select Name
from UnknownTable
where [Date] = 
    (select Max([Date]) 
     from UnknownTable
     where [Date] <= '2009-02-19')

This assumes there are no time components to your date values.

JeremyDWill
A: 

You could do something like this

SELECT TOP 2 [Date] ,[User] FROM [LearningDatabase].[dbo].[Users] WHERE [Date] = '07/15/2009' OR [Date] < '07/15/2009'

Michael Ciba
OP only wanted records with earlier dates if no record was found on date asked for.
Shannon Severance