Question: I'm trying to write a SQL Query that has to return how many transactions were made in the last 10 minutes for each minute. Like:

1 minute ago : 2 transactions

2 minutes ago : 1 transaction

...

9 minutes ago : 3 transactions

10 minutes ago : 4 transactions

I was trying to do this query:

```
 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;

```

I still don't know if the logic is right. What I know is that I'm receiving the error:

> 
> Each GROUP BY expression must contain at least one column that is not an outer reference.
> 
> 
> 

Why I'm having this error? Is there a better way to do the query?

Answer: 
You don't need a numbers table for this, unless you need to fill in times with no transactions. I would start with this:

```
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;

```
I managed to solve my problem in two different ways:

```
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;

```

that has as output:

```
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

```

and with:

```
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)

```

that has as output:

```
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

```