SQL每月平均值(自动)

时间:2017-10-23 11:35:18

标签: sql-server-2014

如何统计SQL中的平均使用日期?

例如,我可以使用今天() - 20171001来计算它在excel中的平均使用率是22,它是自动的。

我需要计算2017年10月到今天计算机的平均值。

表:计算机数据

date       |    property   |    computer code | value
----------      --------        -----------    -------
20160131   |   companyA   |     256584        | 1,000
20160131   |   companyB   |     987451        | 1,200
...
20171022   |   companyA   |     157489        | 1,600
20171022   |   companyA   |     589741        | 1,400
20171022   |   comapnyA   |     547182        | 2,750

SQL:

select property
,sum (case when  property = 'companyA' then value end) / ( the code I have asked - the answer should be 22, 20171023-20171001) as avgvalue_computer

from computer table

group by property
order by property

我想要的结果

property | avgvalue_computer
companyA | 8,500         <- 2017-Oct-01 to 2017-Oct-23 (today)
companyB | 16,800        <- 2017-Oct-01 to 2017-Oct-23 (today)

2 个答案:

答案 0 :(得分:0)

    DECLARE @Table TABLE (Date DATE, Property VARCHAR(20), PropertyCode INT, [Value] FLOAT)
INSERT INTO @Table VALUES
('20161031','cA', 256584, 1000)
SELECT Property CompanyName, MTD.Value, MTD.DateFrom, MTD.DateTo
FROM @Table T1
CROSS APPLY (SELECT AVG(VALUE) Value, DATEADD (D,
                                DATEPART(DAY, GETDATE()) *-1, 
                                 GETDATE()) DateFrom, GETDATE() DateTo
           FROM @Table T2
           WHERE T2.PropertyCode = T1.PropertyCode
           AND T2.Date BETWEEN (DATEADD (D,
                                DATEPART(DAY, GETDATE()) *-1, 
                                 GETDATE())) 
                    AND     GETDATE()
       ) MTD

答案 1 :(得分:0)

选择属性 ,sum(财产=&#39; companyA&#39;然后价值结束)/ datediff(day,&#39; 20171001&#39;,getdate()))作为avgvalue_computer

来自电脑桌

按属性分组 按物业排序