我有一个3列的数据集 - 名称,日期时间,值
例如:
Name DateTime value
----------------------------
A 1/1/2011 1:00:00 626
A 1/1/2011 2:00:00 2311
B 1/1/2011 3:00:00 775
A 1/1/2011 4:00:00 6621
A 1/1/2011 5:00:00 8491
B 1/1/2011 6:00:00 9061
B 1/1/2011 7:00:00 3611
B 1/2/2011 4:00:00 5491
A 1/2/2011 5:00:00 21
我希望将按名称和24小时分组的值相加但不重复(如果我使用了一行,我不想重复使用它)
预期价值:
Name Value
A 2368
B 2042
B 549
A 2
我使用while
循环在24小时内使用唯一索引标记出现并且它可以正常运行,因为我有大数据表
答案 0 :(得分:2)
试试这种方式
select Name,SUM(Value) from Tblname group by Name,CONVERT(date,[Datetime],106)
答案 1 :(得分:1)
原:
SELECT
name
, CAST([DateTime] AS date) AS [Date]
, SUM(value)
FROM YourTable
WHERE [DateTime] >= '20110101'
AND [DateTime] < '20120101'
GROUP BY
name
, CAST([DateTime] AS date)
回应此评论:
你想&#34;推&#34;存储的数据需要2小时,所以通过 DATEADD(小时,2,[日期时间])进行,然后根据需要调整单位和数量。
SELECT
name
, CAST( DATEADD(hour,2,[DateTime]) AS date) AS [Date]
, SUM(value)
FROM YourTable
WHERE [DateTime] >= '20110101'
AND [DateTime] < '20120101'
GROUP BY
name
, CAST( DATEADD(hour,2,[DateTime]) AS date)
注意:如果您尝试使用恒定的2小时调整时区的效果,如果您有夏令时&#34;那么调整并不总是准确的。周期。为此,可能值得这样做:
DECLARE @tzadjust AS INT = DATEDIFF(minute,getutcdate(),getdate())
SELECT
name
, CAST( DATEADD(minute,@tzadjust,[DateTime]) AS date) AS [Date]
, SUM(value)
FROM YourTable
WHERE [DateTime] >= '20110101'
AND [DateTime] < '20120101'
GROUP BY
name
, CAST( DATEADD(minute,@tzadjust,[DateTime]) AS date)
您可以通过以下方式检查差异:
SELECT DATEDIFF(minute,getutcdate(),getdate())
答案 2 :(得分:0)
我找到了一个解决方案:在24小时内找到每个名字的最大值,然后检查哪个日期是第一个,并包括当前发生的日期
SET NOCOUNT ON;
CREATE TABLE #Temp
(
Name varchar(128)
,[Date] DATETIME
,[Value] INT
);
INSERT INTO #Temp
SELECT 'A','2011-01-01 1:00:00',626
UNION ALL SELECT 'A','2011-01-01 2:00:00',231
UNION ALL SELECT 'B','2011-01-01 3:00:00',775
UNION ALL SELECT 'A','2011-01-01 4:00:00',662
UNION ALL SELECT 'A','2011-01-01 5:00:00',849
UNION ALL SELECT 'B','2011-01-01 6:00:00',906
UNION ALL SELECT 'B','2011-01-01 7:00:00',361
UNION ALL SELECT 'B','2011-01-02 4:00:00',549
UNION ALL SELECT 'A','2011-01-02 5:00:00',2
UNION ALL SELECT 'A','2011-01-03 4:00:00',1
SELECT * FROM #Temp
order by [Date];
select Name,[Date],[Value],(select max([Date]) from #temp t2
where t2.Name=t1.Name and t2.[Date] between t1.[Date] and dateadd(hour,24,t1.[Date])) MaxVal
into #temp2
from #temp t1
select *,(select min(date) from #temp2 t2 where t1.[Date] between t2.[Date] and t2.MaxVal and t1.Name=t2.Name ) MinOfMax
into #temp3
from #temp2 t1
select Name,sum(value)
from #temp3
group by Name,MinOfMax