SQL-将每日数据转换为一个月的平均值,直到月底为止的累计总和
我每天都有来自数据库的数据。 它的表包含许多列-日期,实体名称,值1,值2,值3,.. 我想算出每个实体每月的平均值。同样对于某些值,我需要从月初到月末的累计总和值(到月末为止的累计总和)。
示例:
Date Entity Value1 Value2 Value3 Value4
01/01/2017 'ZZ-01' 5 10 25 10
01/01/2017 'BB-01' 5 10 25 10
02/01/2017 'ZZ-01' 2 1 5 0
02/01/2017 'BB-01' 2 1 5 0
03/01/2017 'ZZ-01' 5 10 25 10
03/01/2017 'BB-01' 5 10 25 10
.....
.....
31/01/2017 'ZZ-01' 5 10 25 10
31/01/2017 'BB-01' 5 10 25 5
01/02/2017 'ZZ-01' 5 10 25 15
01/02/2017 'BB-01' 5 10 25 11
02/02/2017 'ZZ-01' 5 10 25 15
.......
28/02/2017 'ZZ-01' 5 10 25 10
28/02/2017 'BB-01' 5 10 25 10
....
以此类推
我要创建的表格如下:
Month Entity AvgValue1 AvgValue2 CumValue2 AvgValue3 AvgValue4
Jan-2017 'ZZ-01' Avg1 Avg2 CumV2 Avg3 Avg4
Jan-2017 'BB-01'
Feb-2017 'ZZ-01'
Feb-2017 'BB-01'
Mar-2017 'ZZ-01'
...
每个值在给定月份的平均值。对于某些值,我需要自表中数据开始到月底为止的累计总和。
通过搜索stackoverflow,我发现我可以使用以下内容来获取总和和
SELECT Date, Name, Sum, Avg,
(SELECT SUM(Value1)
FROM mytable as t2
Where t2.Date <=t1.Date) as CumVal
from mytable as t1
order by t1.DateO ASC, Name
及以下表示该月的平均值
SELECT
dateadd(month, datediff(month, 0, t2.Date), 0) as Month,
AVG(t2.Value1) as AvgValue1
FROM mytable as t2
group by dateadd(month, datediff(month, 0, t2.Date), 0)
但是我无法将这些内容组合在一起以进行一个有助于创建表的查询。感谢您的帮助。
我试图用一个value列创建小的测试代码:
IF OBJECT_ID('dbo.mytable', 'U') IS NOT NULL
BEGIN
DROP TABLE dbo.mytable
END
CREATE TABLE mytable
([DateOn] datetime, [Name] varchar(10), [Rate1] float, [Rate2] float,
[Rate3] float)
;
INSERT INTO mytable
([DateOn], [Name], [Rate1])
VALUES
-- MM/DD/YYYY format
-- value for first 4 days is shown. assume that the rest days are zero
-- average will be (sum /31) in January
('01/01/2017' , 'AA-01', 10),
('01/01/2017' , 'BB-01', 100),
('01/02/2017' , 'AA-01', 15),
('01/02/2017' , 'BB-01', 200),
('01/03/2017' , 'AA-01', 20),
('01/03/2017' , 'BB-01', 300),
('01/04/2017' , 'AA-01', 25),
('01/04/2017' , 'BB-01', 400),
('02/01/2017' , 'AA-01', 10),
('02/01/2017' , 'BB-01', 100),
('02/02/2017' , 'AA-01', 15),
('02/02/2017' , 'BB-01', 200),
('02/03/2017' , 'AA-01', 20),
('02/03/2017' , 'BB-01', 300),
('02/04/2017' , 'AA-01', 25),
('02/04/2017' , 'BB-01', 400)
;
Select dateadd(month, datediff(month, 0, t1.DateOn), 0) as Month, Name,
AVG(t1.Rate1) as AvgRate1,
(
SELECT SUM(Rate1)
FROM mytable as t2
Where t2.DateOn <=t1.DateOn
)
as CumRate
from mytable as t1
--order by t1.DateOn ASC,Name
group by dateadd(month, datediff(month, 0, t1.DateOn), 0)
DROP TABLE dbo.mytable
我正在运行此测试 https://rextester.com/CFHEW85984
但出现错误:
错误,警告: 选择列表中的'mytable.DateOn'列无效,因为它不是 包含在聚合函数或GROUP BY子句中。
选择列表中的'mytable.Name'列无效,因为它既不包含在聚合函数中也不在GROUP BY子句中。
预期结果表格式:
Month Name AvgRate CumRate
Jan-17 AA-01 2.258 70
Jan-17 BB-01 32.258 1000
Feb-17 AA-01 2.5 140
Feb-27 BB-01 35.714 2000
因此,对于1月17日(名称为AA-01),我将每日数字相加(在此示例中仅4天,其余假设为0)并除以31得到该月的平均值。然后,我对它们求和以求累积。对于2月份,平均值的计算方法与w相同,但累计值为cum_jan + cum_feb。如此
我也在努力将其与join相结合。