Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

SQL Server datetime filter query

I have this query in 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];

result of this query has record with [Order Date] of 2012-06-21 00:00:00.000

but with this query

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];

I don't get this record.

Does SQL Server have any properties that is missing here?

Hint: type of [Order Date] is datetime.

question from:https://stackoverflow.com/questions/65952835/how-to-get-the-data-of-specific-date-when-the-datetime-is-stored-in-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

SQL Server date/time columns have precisions that vary depending on the exact type. In your first, the "0.999" is being rounded up.

The safest approach is to eschew between and the time components, with something like:

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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...