Sle*_*lee 9 sql-server sql-server-2005
我需要根据日期对某些记录进行分组,但它是一个日期和时间字段,我需要忽略时间部分,只需按日期部分进行分组 - 这是我现在的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
Run Code Online (Sandbox Code Playgroud)
cas*_*One 23
你可以这样分组:
cast(floor(cast(AutoShipItems.NextOrderDate as float)) as datetime)
Run Code Online (Sandbox Code Playgroud)
我将它放入标量用户定义函数中以使其更容易:
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
Run Code Online (Sandbox Code Playgroud)
然后你会这样打电话:
GROUP BY
AutoShipItems.CustomerID,
dbo.xfn_TrimTimeFromDateTime(AutoShipItems.NextOrderDate),
Customer.FirstName, Customer.LastName, Customer.EmailAddress
Run Code Online (Sandbox Code Playgroud)
请注意,您可能必须更改SELECT子句中的值,因为您现在正在按不同的方式进行分组.
mso*_*son 14
cast (x as date)
Run Code Online (Sandbox Code Playgroud)
要么
year(x)
month(x)
day(x)
Run Code Online (Sandbox Code Playgroud)