2017-09-02 236 views
0

我有這個疑問在SQL Server:SQL Server日期時間篩選查詢

此查詢的
SELECT 
    [Order Date], SUM([Profit]) 
FROM 
    [sample].[dbo].[superstore] 
WHERE 
    [Order Date] BETWEEN '2012-06-21 00:00:00.000' AND '2012-09-21 23:59:59.999' 
GROUP BY 
    [Order Date] 
ORDER BY 
    [Order Date]; 

結果有紀錄的2012-06-21 00:00:00.000

[訂購日期],但與此查詢

SELECT 
    [Order Date], SUM([Profit]) 
FROM 
    [sample].[dbo].[superstore] 
WHERE 
    [Order Date] BETWEEN '2012-06-21 00:00:00.000' AND '2012-09-21 23:59:59.998' 
GROUP BY 
    [Order Date] 
ORDER BY 
    [Order Date]; 

我沒有得到這個記錄。

SQL Server是否有任何缺少的屬性?

提示:類型[Order Date]datetime

+0

' SQL Server中的DATETIME'具有3.33ms的精度,導致這些奇怪的四捨五入效應。建議使用SQL Server 2008中引入的'DATETIME2(n)','DATE'和'TIME' - 這些類型沒有這種奇怪的準確性和舍入問題 –

回答

3

SQL Server日期/時間列的精度取決於確切的類型。在你的第一個,「0.999」正在四捨五入。

最安全的方法是避開between和時間成分,具有類似:

SELECT [Order Date] , sum([Profit]) 
FROM [sample].[dbo].[superstore] 
WHERE [Order Date] >= '2012-06-21' AND 
     [Order Date] < '2012-09-22' 
GROUP BY [Order Date] 
ORDER BY [Order Date]; 
1

使用BETWEEN操作日期範圍起初似乎吸引人,但正如你發現了,這是一個頭疼。如果你堅持以下格式,你會發現它不管日期/時間數據類型。

注:凡之間的邏輯> =和< =,我們的轉移「的最後一天,到次日午夜

SELECT 
    [Order Date], SUM(Profit) 
FROM 
    sample.dbo.superstore 
WHERE 
    [Order Date] >= '2012-06-21' 
    AND [Order Date] < '2012-09-22' 
GROUP BY 
    [Order Date] 
ORDER BY 
    [Order Date]; 
2

使用下面的查詢

SELECT 
    CAST([Order Date] AS date), 
    SUM([Profit]) 
FROM [sample].[dbo].[superstore] 
WHERE CAST([Order Date] AS date) BETWEEN '2012-06-21' AND '2012-09-21' 
GROUP BY CAST([Order Date] AS date) 
ORDER BY CAST([Order Date] AS date);