以24小时块的形式对SUM数据进行分组

时间:2012-06-05 16:08:46

标签: sql sql-server sql-server-2008

我在Microsoft SQL Server 2008中有数据需要SUM。我需要将这笔款项分组24小时。 24小时是从第二天的下午3:00到第二天的下午3:00。

例如

  

DateExited,Value

     

2012年1月1日15:00,5

     

2012年1月1日15:04,6

     

2012年1月1日17:00,7

     

1/2/2012 00:00,-5

     

1/2/2012 09:00,10

     

1/2/2012 15:00,31

总和应为54.我有以下查询,但是将所有内容分组,从午夜到午夜,而不是下午3:00到下午3:00

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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)

答案 2 :(得分: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

答案 3 :(得分: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