我有一张包含时间(列)和功率(列)的表格。我想在下表数据上计算不同的结果集:
我的表:
[timestamp] [power]
2016-01-06 13:32:27 1
2016-01-06 13:33:27 2
2016-01-06 13:34:27 3
2016-01-06 13:35:27 4
2016-01-06 13:36:27 5
2016-01-06 13:37:27 6
2016-01-06 13:38:27 7
2016-01-06 13:39:27 8
2016-01-06 13:40:27 9
2016-01-06 13:41:27 10
总计:
[timestamp] [power] Total
2016-01-06 13:32:27 1 1
2016-01-06 13:33:27 2 3
2016-01-06 13:34:27 3 6
2016-01-06 13:35:27 4 10
2016-01-06 13:36:27 5 15
2016-01-06 13:37:27 6 21
2016-01-06 13:38:27 7 28
2016-01-06 13:39:27 8 36
2016-01-06 13:40:27 9 45
2016-01-06 13:41:27 10 55
每5分钟的总数为:
[timestamp] [power] Total_every_5minutes
--2016-01-06 13:32:27 1 1
--2016-01-06 13:33:27 2 3
--2016-01-06 13:34:27 3 6
--2016-01-06 13:35:27 4 10
2016-01-06 13:36:27 5 15
--2016-01-06 13:37:27 6 21
--2016-01-06 13:38:27 7 28
--2016-01-06 13:39:27 8 36
2016-01-06 13:40:27 9 45
类似地,我想计算平均值,最小值,最大值,标准偏差,&计数。截至目前,我已经编写了一个查询,其中将添加一列
请注意:
我不应该写存储过程。由于我有一个用户选择数据库的Windows应用程序,它将列出表,从列出的表中用户选择列,并在特定列上设置计算总数等。选择后,查询正在构建。并且查询将执行并将结果绑定到datagridview
。
IF OBJECT_ID('tempdb..#mytemptable') IS NOT NULL DROP TABLE #mytemptable;
SELECT SUM( CAST ([power] AS bigint) ) AS power_TOTAL INTO #MYTEMPTABLE
FROM ( SELECT t1.[timestamp], t1.[power] FROM [REPORT] t1 ) TEMPTABLE
SELECT t1.[timestamp], t1.[power], RM_temp.* FROM [REPORT] t1 , #MYTEMPTABLE RM_temp;
答案 0 :(得分:0)
可能会根据您的数据
为您服务DECLARE @Table1 TABLE
( timestamp varchar(19), power int)
;
INSERT INTO @Table1
( timestamp , power )
VALUES
('2016-01-06 13:32:27', 1),
('2016-01-06 13:33:27', 2),
('2016-01-06 13:34:27', 3),
('2016-01-06 13:35:27', 4),
('2016-01-06 13:36:27', 5),
('2016-01-06 13:37:27', 6),
('2016-01-06 13:38:27', 7),
('2016-01-06 13:39:27', 8),
('2016-01-06 13:40:27', 9),
('2016-01-06 13:41:27', 10)
;
Select [timestamp],[power] from (
SELECT timestamp, power , RunningTotal = power + COALESCE(
(
SELECT SUM(power)
FROM @Table1 AS i
WHERE i.timestamp < o.timestamp), 0
)
FROM @Table1 AS o)TT where exists (Select * from (select power * 5 ID from @Table1) T WHERE T.id = TT.RunningTotal )
ORDER BY timestamp;