计算每分钟的最后10个数据

时间:2017-10-31 13:42:57

标签: sql sql-server datetime group-by

我正在尝试编写一个SQL查询,该查询必须返回每分钟最近10分钟内完成的事务数。像:

1分钟前:2笔交易

2分钟前:1次交易

...

9分钟前:3笔交易

10分钟前:4笔交易

我正在尝试执行此查询:

 DECLARE @N int =  10;
 DECLARE @NOW DATETIME =  GETDATE();

 WITH numbers( num ) AS (
     SELECT 1 UNION ALL
     SELECT 1 + num FROM numbers WHERE num < @N )

 SELECT num AS minute,
 ( 
     SELECT COUNT(*) AS RESULTS
     FROM  [ApiTransactions] 
     WHERE [DateUtc] > DATEADD(year, -1, @NOW)
     GROUP BY DATEPART(minute, DATEADD(minute, -num, @NOW))

 )
 FROM numbers;

我仍然不知道逻辑是否正确。我所知道的是我收到了错误:

  

每个GROUP BY表达式必须至少包含一个不是外部引用的列。

为什么我出现此错误?有没有更好的方法来进行查询?

3 个答案:

答案 0 :(得分:3)

除非您需要填写没有交易的时间,否则您不需要数字表。我会从这开始:

SELECT DATEADD(minute, DATEDIFF(minute, 0, DateUtc), 0) as the_minute, COUNT(*)
FROM ApiTransactions
WHERE DateUtc > DATEADD(minute, -10, DateUtc)
GROUP BY DATEADD(minute, DATEDIFF(minute, 0, DateUtc), 0)
ORDER BY the_minute;

答案 1 :(得分:0)

你可以使用这个:

branch init
initSession success
{+clicked_branch_link: false, +is_first_session: false}

输出:

SELECT  DATEDIFF(minute,[DateUtc],GETDATE()) as minutes_ago,
        COUNT(*) tran_count 
FROM ApiTransactions
WHERE DATEDIFF(second,[DateUtc],GETDATE()) <= 600 -- 10 minutes ago
GROUP BY DATEDIFF(minute,[DateUtc],GETDATE())

答案 2 :(得分:0)

我设法用两种不同的方式解决了我的问题:

DECLARE @N int =  10;
DECLARE @NOW DATETIME = GETDATE();

WITH numbers( num ) AS (
SELECT 1 UNION ALL
SELECT 1 + num FROM numbers WHERE num < @N )

SELECT num-1 AS minute,
( 

SELECT COUNT(*) AS RESULTS
FROM  [ApiTransactions] 
WHERE [DateUtc] > DATEADD(minute, -num, @NOW) AND [DateUtc] < DATEADD(minute, -num+1, @NOW)

)
FROM numbers;

具有输出:

minutes_ago    amount 
0               4             (most recents. still being updated)

1               0

2               2

3               3

4               1

5               2

6               1

7               2

8               1

9               3

和:

DECLARE @NOW DATETIME = GETDATE();
SELECT CONVERT(int, DATEDIFF(second, [DateUtc], @NOW)/60) as TimePassed, COUNT([TypeCode]) as Amount
FROM [ApiTransactions]
WHERE [DateUtc] >= DATEADD (minute, -10 , @NOW)
GROUP BY CONVERT(int, DATEDIFF(second, [DateUtc], @NOW)/60)
ORDER BY  CONVERT(int, DATEDIFF(second, [DateUtc], @NOW)/60)

具有输出:

minutes_ago    amount 
0               4             (most recents. still being updated)

2               2

3               3

4               1

5               2

6               1

7               2

8               1

9               3