1

我在 Microsoft SQL Server 2008 中有需要求和的数据。问题是我需要按 24 小时的时间段对总和进行分组。24 小时时段是从一天下午 3:00 到第二天下午 3:00。

例如

退出日期,值

1/1/2012 15:00, 5

1/1/2012 15:04, 6

1/1/2012 17:00, 7

2012 年 1 月 2 日 00:00,-5

1/2/2012 09:00, 10

1/2/2012 15:00, 31

总和应该是 54。我有以下查询,但是它将午夜到午夜的所有内容分组,而不是 3:00 pm 到 3:00 pm

SELECT dateadd(day,datediff(day,0, dateadd(hh, 0, DateExited) ),0) As SummaryDate, SUM(Value) as s1
FROM Test
where DateExited BETWEEN dateadd(year,datediff(year,0,GETDATE()),0) AND GetDate()
GROUP BY dateadd(day,datediff(day,0, dateadd(hh, 0, DateExited) ),0)
ORDER BY SummaryDate
4

4 回答 4

1

从您的日期/时间值中减去 15 小时应该可以得到您正在寻找的结果。

此外,使用 SQL 2008,您可以将日期时间转换为日期,而不是将天数添加到 0。

SELECT CONVERT(DATE, DATEADD(hour, -15, DateExited)) As SummaryDate, SUM(Value) as s1
FROM Test
WHERE DATEADD(hour, -15, DateExited) BETWEEN @StartDate AND @EndDate
GROUP BY CONVERT(DATE, DATEADD(hour, -15, DateExited))
ORDER BY SummaryDate
于 2012-06-05T16:15:04.130 回答
1

您可以添加负 15 小时,然后将结果转换为日期:

select  cast(dateadd(hour,-15,'2012-05-06 14:30') as date) -- 2012-05-05
select  cast(dateadd(hour,-15,'2012-05-06 15:30') as date) -- 2012-05-06

给你一个group by赞:

group by cast(dateadd(hour,-15,'2012-05-06 03:30') as date)
于 2012-06-05T16:16:45.863 回答
0

您可以创建一个函数来返回给定日期输入参数所需的值:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION GetValueSum 
(
    @StartDate DATETIME
)
RETURNS INT
AS
BEGIN
DECLARE @ValueSum INT
DECLARE @StartDateTime DATETIME
DECLARE @EndDateTime DATETIME

-- Set the starting time to 3 PM on the datetime sent in:
SET @StartDateTime = DATEADD(hh, 15, CAST(CAST(@StartDate AS DATETIME) AS DATETIME))

-- Set the end time to one day later, minus 3 milliseconds (this smallest unit sql server can use)
SET @EndDateTime = DATEADD(ms, -3, DATEADD(dd, 1, @StartDateTime))

SELECT @ValueSum = SUM(Value)
FROM dbo.test
WHERE DateExited BETWEEN @StartDateTime AND @EndDateTime

RETURN @ValueSum

END
GO
于 2012-06-05T16:32:13.893 回答
0

最简单的方法是投射到日期:

SELECT cast(SummaryDate as date), SUM(Value) as s1
FROM Test
where DateExited BETWEEN dateadd(year,datediff(year,0,GETDATE()),0) AND GetDate()
GROUP BY cast(SummaryDate as date)
ORDER BY 1
于 2012-06-05T16:14:12.510 回答