count without group

試著忘記壹切 提交于 2019-11-27 12:05:23

问题


I have one table named GUYS(ID,NAME,PHONE) and i need to add a count of how many guys have the same name and at the same time show all of them so i can't group them. example:

ID NAME  PHONE
1  John  335   
2  Harry 444
3  James 367
4  John  742
5  John  654

the wanted output should be

ID NAME  PHONE COUNT
1  John  335   3
2  Harry 444   1
3  James 367   1
4  John  742   3
5  John  654   3

how could i do that? i only manage to get lot of guys with different counts.

thanks


回答1:


Use an aggregate Query:

select g.ID, g.Name, g.Phone, count(*) over ( partition by g.name ) as Count
from 
Guys g;



回答2:


Since MySQL doesn't have analytical functions like Oracle, you'll have to resort to a sub-query.

Don't use GROUP BY, use a sub-select to count the number of guys with the same name:

SELECT
  t.name,
  t.phone,
  (SELECT COUNT('x') FROM Guys ct 
   WHERE ct.name = t.name) as namecounter
FROM
  Guys t

You'd think that running a sub-select for every row would be slow, but if you've got proper indexes, MySQL will optimize this query and you'll see that it runs just fine.

In this example, you should have an index on Guys.name. If you have multiple columns in the where clause of the subquery, the query would probably benefit from a single combined index on all of those columns.




回答3:


You can still use a GROUP BY for the count, you just need to JOIN it back to your original table to get all the records, like this:

select g.ID, g.Name, g.Phone, gc.Count
from Guys g
inner join (
    select Name, count(*) as Count
    from Guys
    group by Name
) gc on g.Name = gc.Name



回答4:


In Oracle DB you can use

SELECT ID,NAME,PHONE,(Select COUNT(ID)From GUYS GROUP BY Name) FROM GUYS ;




回答5:


select id, name, phone,(select count(name) from users u1 where u1.name=u2.name) count from users u2


来源:https://stackoverflow.com/questions/4259611/count-without-group

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