SQL Server - monthly avg of count

Deadly 提交于 2019-12-14 03:34:35

问题


I want to be able to find out the monthly average of a count

My code at the moment is

SELECT 
    company, 
    COUNT(company) AS 'count'
FROM Information
GROUP BY company

I basically need it to be

SELECT company, 
       count(company) as 'count'
       avg(count(company)) per month as 'average'
FROM Information
group by company

I want the result to look something like this

company count   monthly average
a       5       6
b       13      14
c       2       2
d       45      45
e       23      21
f       6       5

回答1:


A very simple approach would be to count per company and month first and then aggregate this data to get total and avarage per company.

select
  company,
  sum(cnt) as records,
  avg(cnt) as records_per_month
from
(
  select company, year(start_date), month(start_date), count(*) as cnt
  from information
  group by company, year(start_date), month(start_date)
) agg
group by company;

But read my comment to your question.




回答2:


SELECT YEAR(yourDate) * 100 + MONTH(yourDate) YYMM,
        company, 
        count(company) as 'count'
        avg(count(company)) per month as 'average'
FROM Information
group by company
,YEAR(yourDate) * 100 + MONTH(yourDate)


来源:https://stackoverflow.com/questions/37594746/sql-server-monthly-avg-of-count

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!