[英]T-SQL to trim a datetime to the nearest date?
Duplicate of What's the BEST way to remove the time portion of a datetime value (SQL Server)? 重复 什么是去除datetime值(SQL Server)的时间部分的最佳方式?
I have a column that tracks when things are created using a datetime, but I'd like to generate a report that groups them by day, so I need a way of nulling out the time component of a datetime column. 我有一个列来跟踪使用日期时间创建事物的列,但是我想生成一个按日分组的报表,所以我需要一种方法来清空datetime列的时间组件。
How do I do this? 我该怎么做呢?
Why not convert straight to date: 为什么不直接转换为日期:
select convert(date, getdate())
This truncates days, not rounds. 这截断了几天而不是几轮。 To round Days do this:
圆形天做这个:
select convert(date, getdate() + 0.5)
一种方法是将getdate()
更改为列名,
select dateadd(dd, datediff(dd, 0, getdate())+0, 0)
这是另一个解决方案:
SELECT CAST( FLOOR( CAST( GETDATE() AS float) ) AS smalldatetime)
This is a simple way to get the date (as a string) from a datetime: 这是从日期时间获取日期(作为字符串)的简单方法:
convert(varchar, <the date field/value/etc>, 101)
But note that ordering on this field will be alphabetical rather than by date since it's now a string 但请注意,此字段的排序将按字母顺序排列,而不是按日期排序,因为它现在是一个字符串
Yes. 是。 There are many formats to choose from so I'll link it instead.
有很多格式可供选择,所以我会链接它。
http://library.cirr.com/Microsoft/SQL-Server-v7/html/ca-co_1.htm http://library.cirr.com/Microsoft/SQL-Server-v7/html/ca-co_1.htm
If you wish to zero out the time like your post implies, you can try this: 如果您希望将帖子隐含的时间归零,可以试试这个:
select cast(convert(varchar, getdate(), 101) as datetime)
我只是做演员(getdate()作为日期)
declare @CurrentDate datetime
set @CurrentDate = dateadd(dd, datediff(dd, 0, getdate()), 0)
--or-- - 要么 -
select dateadd(dd, datediff(dd, 0, MyDateColumn), 0) as DateOnly
from tblX
In my searches I came across the following solution, it strips time out of UTC time only, but I found it interesting, so I thought someone else would too: 在我的搜索中,我遇到了以下解决方案,它只消除了UTC时间的时间,但我发现它很有趣,所以我认为其他人也会这样:
FUNCTION TrimDate(@dt AS DATETIME) RETURNS DATETIME
BEGIN
RETURN CAST(CAST((@dt - 0.500000038580247) AS INT) AS DATETIME)
END
I would presume that it runs quickly since all it's doing is rounding and casting. 我认为它运行得很快,因为它所做的只是四舍五入和铸造。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.