简体   繁体   中英

T-SQL Count all rows and group by id

i have a little problem with sql. I need help by a query where is can count all rows and group by the id. I need this, because i need to get the average of logins.

Table have this: MRr, date

MNr 3 => 5 entries

MNr 4 => 2 entries

MNr 5 => 7 entries

And now i need to result all MNr with entries count more than 50% of all average. Like: (5+2+7)/3 = 4,666 and the result are MNr 3 and MNr 5.

I tried this with something like AVG(COUNT(date)) but it doesnt work.

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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM