我需要根据日期对某些记录进行分组,但它是一个日期和时间字段,我需要忽略时间部分,只需按日期部分进行分组 - 这是我现在的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子句中的值,因为您现在正在按不同的方式进行分组.
你可以这样分组:
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子句中的值,因为您现在正在按不同的方式进行分组.
cast (x as date)
要么
year(x) month(x) day(x)