[英]T-SQL Count all rows and group by id
i have a little problem with sql. 我对sql有一点问题。 I need help by a query where is can count all rows and group by the id.
我需要一个查询来帮助,该查询可以计算所有行并按ID分组。 I need this, because i need to get the average of logins.
我需要这个,因为我需要获取平均登录次数。
Table have this: MRr, date 表格有:MRr,日期
MNr 3 => 5 entries MNr 3 => 5个条目
MNr 4 => 2 entries MNr 4 => 2个条目
MNr 5 => 7 entries MNr 5 => 7个条目
And now i need to result all MNr with entries count more than 50% of all average. 现在我需要得出所有MNr的条目数超过所有平均值的50%。 Like:
(5+2+7)/3 = 4,666
and the result are MNr 3 and MNr 5. 像:
(5+2+7)/3 = 4,666
4,666,结果是MNr 3和MNr 5。
I tried this with something like AVG(COUNT(date))
but it doesnt work. 我尝试使用
AVG(COUNT(date))
类的方法尝试此操作,但是它不起作用。
I hope you guys know what i mean... hard to explain for me sorry. 我希望你们知道我的意思...对不起,我很难解释。
Greetz 格蕾兹
You seem to want the MNR that have more than the average number of logins for an MNR. 您似乎希望MNR拥有比MNR的平均登录数更多的MNR。 Here is a method that uses window functions:
这是使用窗口函数的方法:
select mnr, cnt
from (select mnr, count(*) as cnt, avg(1.0*count(*)) over () as avg
from table t
group by mnr
) t
where cnt > avg;
An alternative solution: 替代解决方案:
select MRr, count(*) as _count
from mnr
group by MRr
having count(*) > (select count(*) / count(distinct mrr) * 1.0 from mnr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.