2009-07-18 74 views
3

我有兩列DateUser SQL表,其中包含以下行:如何在SQL Server中爲以下情況編寫我的WHERE子句?

**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 

給定一個日期,應該怎麼寫我的WHERE子句來回報廣大用戶的列表該日期,或者如果沒有在該日期找到用戶用戶,返回下一個較早日期的用戶列表。例如,如果給定日期是'2009-02-19',則返回的用戶列表應該是WilliamAbner

回答

6
SELECT User 
FROM MyTable 
WHERE MyDate = (SELECT MAX(MyDate) FROM MyTable WHERE MyDate <= '2009-02-19') 
+0

你有一個額外的)......它應該是 其中date =(SELECT MAX(指明MyDate)FROM MyTable的WHERE指明MyDate <=「2009-02-19 ') – 2009-07-18 13:45:45

+1

+1只是因爲它有如此輝煌的答案。 :P – AnthonyWJones 2009-07-18 21:57:12

0
SELECT * 
FROM [MyTable] t 
INNER JOIN 
    ( 
     SELECT TOP 1 [Date] 
     FROM [MyTable] 
     WHERE [Date] >= @TargetDate 
     ORDER BY [Date] 
    ) d ON t.[Date] = d.[Date] 
5
SELECT [User] FROM myTable WHERE Date = 
    (SELECT Max(Date) FROM myTable WHERE Date <= '2009-02-19') 
+0

當我之前寫了完全相同的東西時,這會如何被投票? *劃痕頭* – cletus 2009-07-18 13:49:08

0

事情是這樣的:

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

這是假設沒有時間部件您的日期值。

-1

你可以做這樣的事情

SELECT TOP 2 [日期] ,[用戶] FROM [LearningDatabase] [DBO]。[用戶] WHERE [日期] = '07 /2009分之15 ' 或[日期] < '07/15/2009' 的