我试图创建一个新列,其变量在给定条件子句的情况下递增。
这是我的疑问:
SELECT
[timestamp],
[load],
[timestamp] % 60 AS module,
group_by_column = CASE WHEN ([timestamp] % 60)= 0 then 1 else 0 end
FROM
table_01
这是我的回报:
timestamp load module group_by_column
1432592618 24 38 0
1432592619 32 39 0
1432592620 21 40 0
1432592621 31 41 0
1432592622 28 42 0
1432592640 22 0 1
1432592641 31 1 0
1432592642 39 2 0
1432592643 33 3 0
1432592644 36 4 0
1432592649 32 9 0
1432592698 21 58 0
1432592700 25 0 1
1432592701 20 1 0
1432592702 27 2 0
1432592703 31 3 0
我需要一张这样的表:
timestamp load module group_by_column
1432592618 24 38 0
1432592619 32 39 0
1432592620 21 40 0
1432592621 31 41 0
1432592622 28 42 0
1432592640 22 0 1
1432592641 31 1 1
1432592642 39 2 1
1432592643 33 3 1
1432592644 36 4 1
1432592649 32 9 1
1432592698 21 58 1
1432592700 25 0 2
1432592701 20 1 2
1432592702 27 2 2
1432592703 31 3 2
例如,每当我发现满足条件[timestamp]%60 = 0时,我在第四列中递增。
我不知道这是否是解决此问题的最佳方法,我只需要输出如下所述。
由于
答案 0 :(得分:1)
在SQL Server 2012+中,您将执行累积总和:
SELECT [timestamp], [load], [timestamp] % 60 AS module,
SUM(CASE WHEN [timestamp] % 60 = 0 THEN 1 ELSE 0 END) OVER
(ORDER BY timestamp) as group_by_column
FROM table_01;
在SQL Server 2008中,我认为您可以使用dense_rank()
获得相同的效果:
SELECT [timestamp], [load], [timestamp] % 60 AS module,
DENSE_RANK() OVER (ORDER BY [timestamp] / 60)
FROM table_01;
答案 1 :(得分:0)
如果计数整数应该反映自第一个事件以来经过的分钟数,那么以下内容将起作用:
SELECT [timestamp], [load], [timestamp] % 60 AS module,
([timestamp] / 60) - (SELECT min([timestamp]) / 60 FROM table_01) grp
FROM table_01;