2015-06-30 57 views
0
2012-11-23 05:49:26.000 
2012-11-23 07:55:43.000 
2012-11-23 13:59:56.000 
2012-11-26 07:51:13.000 
2012-11-26 10:23:31.000 
2012-11-26 10:25:09.000 
2012-11-26 16:22:22.000 
2012-11-27 07:30:03.000 
2012-11-27 08:53:47.000 
2012-11-27 10:40:55.000 

從這個當我通過2012-11-27 ....我想分鐘2012-11-27 07:30:03.000輸出,最大2012-11-27 10:40:55.000選擇最小值和最大值日期時間只提供部分日期(年/月/日)

+0

請發表您的當前密碼,您用它具體是什麼問題 –

回答

2

所有您需要理解是日期比較:

where cast(col as date) = '2012-11-27' 

select min(col), max(col) 
from table t 
where col >= '2012-11-27' and 
     col < dateadd(day, 1, '2012-11-27'); 

日期比較,使用兩個比較,而不是很自覺地做

第一種方法是一個好習慣,因爲它更可能導致SQL Server在列上使用索引,特別是對於更復雜的表達式。

+0

Thanks..Its爲me..but的工作是什麼DATEADD背後邏輯(天,1,「2012年11月27日」); –

+0

@ShivajiKokate。 。 。這是第二天最早的時間。所以,邏輯與第二次比較相同,但表達式是可靠的。 –

0
Select Max(DateAttribute) 
     ,Min(DateAttribute) 
From Table As t 
Where Dateadd(D, 0, Datediff(D, 0, DateAttribute)) = @DateFilter ----your parameter 

上面將在SQL Server 2005中工作,也沒有任何改變。

0

我喜歡使用between關鍵字進行日期比較。我還包含一個與您的數據相匹配的示例表聲明。

DECLARE @tempDates AS TABLE (myDate DATETIME) 

INSERT INTO @tempDates VALUES 
('2012-11-23 05:49:26.000'), 
('2012-11-23 07:55:43.000'), 
('2012-11-23 13:59:56.000'), 
('2012-11-26 07:51:13.000'), 
('2012-11-26 10:23:31.000'), 
('2012-11-26 10:25:09.000'), 
('2012-11-26 16:22:22.000'), 
('2012-11-27 07:30:03.000'), 
('2012-11-27 08:53:47.000'), 
('2012-11-27 10:40:55.000') 

SELECT 
    MIN(myDate) AS 'Min', MAX(myDate) AS 'Max' 
FROM 
    @tempDates 
WHERE 
    myDate BETWEEN CONVERT(DATETIME, '2012-11-27') 
    AND DATEADD(D,1, CONVERT(DATETIME, '2012-11-27')) 
相關問題