当前位置:  开发笔记 > 数据库 > 正文

从SQL Server中的选择日期时间列中获取分组中的日期

如何解决《从SQLServer中的选择日期时间列中获取分组中的日期》经验,为你挑选了2个好方法。

我需要根据日期对某些记录进行分组,但它是一个日期和时间字段,我需要忽略时间部分,只需按日期部分进行分组 - 这是我现在的SQL:

SELECT   
    AutoShipItems.CustomerID,AutoShipItems.NextOrderDate,
    Customer.FirstName,Customer.LastName, Customer.EmailAddress
FROM        
    AutoShipItems 
        INNER JOIN    Customer ON 
            AutoShipItems.CustomerID =Customer.CustomerID
WHERE     
    (AutoShipItems.NextOrderDate <= GETDATE())
GROUP BY 
    AutoShipItems.CustomerID, AutoShipItems.NextOrderDate, 
    Customer.FirstName, Customer.LastName, 
    Customer.EmailAddress
ORDER BY 
    AutoShipItems.NextOrderDate

casperOne.. 23

你可以这样分组:

cast(floor(cast(AutoShipItems.NextOrderDate as float)) as datetime)

我将它放入标量用户定义函数中以使其更容易:

create function [dbo].[xfn_TrimTimeFromDateTime]
(
    @date as datetime
)
returns datetime with schemabinding as
begin
    --- Convert to a float, and get the integer that represents it.
    --- And then convert back to datetime.
    return cast(floor(cast(@date as float)) as datetime)
end

然后你会这样打电话:

GROUP BY
    AutoShipItems.CustomerID, 
    dbo.xfn_TrimTimeFromDateTime(AutoShipItems.NextOrderDate), 
    Customer.FirstName, Customer.LastName, Customer.EmailAddress

请注意,您可能必须更改SELECT子句中的值,因为您现在正在按不同的方式进行分组.



1> casperOne..:

你可以这样分组:

cast(floor(cast(AutoShipItems.NextOrderDate as float)) as datetime)

我将它放入标量用户定义函数中以使其更容易:

create function [dbo].[xfn_TrimTimeFromDateTime]
(
    @date as datetime
)
returns datetime with schemabinding as
begin
    --- Convert to a float, and get the integer that represents it.
    --- And then convert back to datetime.
    return cast(floor(cast(@date as float)) as datetime)
end

然后你会这样打电话:

GROUP BY
    AutoShipItems.CustomerID, 
    dbo.xfn_TrimTimeFromDateTime(AutoShipItems.NextOrderDate), 
    Customer.FirstName, Customer.LastName, Customer.EmailAddress

请注意,您可能必须更改SELECT子句中的值,因为您现在正在按不同的方式进行分组.



2> mson..:
cast (x as date)

要么

year(x)
month(x)
day(x)

推荐阅读
可爱的天使keven_464
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有