【发布时间】:2017-10-24 16:15:35
【问题描述】:
SQL中如何计算平均使用天数?
例如,我可以使用 today()-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)
【问题讨论】:
-
也许 datediff(day, '20171001', getdate())?或者也许只是平均(价值)? Avg 还将处理丢失的日期。如果每天有超过一条记录,那么您将需要更多逻辑
-
datediff(day, '20171001', getdate()) 很有用!!!谢谢!!!
标签: sql-server-2014