固定间隔后的平均值和SQL中的Group By

时间:2018-06-12 00:25:41

标签: group-by average

是否可以在每个固定时间间隔后平均并在MSSQL中按一列分组?

假设我有一个表A,如下:

NAME  Interval  Data1  Data2
1      0.01     1      4
1      0.05     4      2
1      0.09     7      6
1      0.11     1      2
1      0.15     7      6
1      0.18     3      1
1      0.19     2      5
2      0.209    9      0

我希望输出按名称分组,并且每10个计数运行一次。 所以对于expamle

Name - 1
Interval Start - 0
Interval End - 10
Data 1 Avg - 4 [(1 + 4 + 7) / 3]
Data 3 Avg - 4 [(4 + 2 + 6) / 3]

Name - 1
Interval Start - 10
Interval End - 20
Data 1 Avg - 3.25 [(1 + 7 + 3 + 2) / 4]
Data 3 Avg - 3.50 [(2 + 6 + 1 + 5) / 4]

所以我想要输出如下。每个"名称"专栏不同。

Name Interval-Start Interval-End DataAvg1  DataAvg2
 1      0                10         4         4
 1      10               20         3.25      3.50
 2      0                10         0         0
 2      10               20         0         0
 2      20               30         9         0

我使用了以下查询,但无法确定每个间隔的逻辑。

SELECT Name, Interval, AVG(Data1) AS Data1Avg, AVG(Data2) AS  Data2Avg
FROM TableA
GROUP BY Name;

有人可以帮助我。

1 个答案:

答案 0 :(得分:1)

使用游标和临时表

--drop table dbo.#result
--drop table dbo.#steps

CREATE TABLE dbo.#result
   (   
   [Name] varchar(50), 
   [Interval-Start] float,
   [Interval-End] float, 
   [DataAvg1] float, 
   [DataAvg2] float
   ) 

CREATE TABLE dbo.#steps
   (   
   [IntervalStart] float,
   [IntervalEnd] float
   ) 

declare @min int, @max int, @step float
DECLARE @Name varchar(50), @IntervalStart float, @IntervalEnd float;  

set @min = 0
set @max = 1
set @step = 0.1

insert into #steps
select @min + Number * @step IntervalStart, @min + Number * @step + @step IntervalEnd
from master..spt_values
where type = 'P' and number between 0 and (@max - @min) / @step


DECLARE _cursor CURSOR FOR
SELECT [Name], [IntervalStart], [IntervalEnd] FROM 
(select [Name] from [TableA] Group by [Name]) t
INNER JOIN #steps on 1=1

OPEN _cursor;  

FETCH NEXT FROM _cursor  
INTO @Name, @IntervalStart, @IntervalEnd;  

WHILE @@FETCH_STATUS = 0  
BEGIN

   insert into dbo.#result
   select @Name, @IntervalStart, @IntervalEnd, AVG(CAST(Data1 as FLOAT)), AVG(CAST(Data2 as FLOAT))
   FROM [TableA]
   where [NAME] = @Name and Interval between @IntervalStart and @IntervalEnd

   FETCH NEXT FROM _cursor  
   INTO @Name, @IntervalStart, @IntervalEnd;  
END  

CLOSE _cursor;  
DEALLOCATE _cursor;

select * from dbo.#result