count without group

我怕爱的太早我们不能终老 提交于 2019-11-28 19:16:17

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.

Sowmia Naraynan

Use an aggregate Query:

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

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
Sayantan Dey

In Oracle DB you can use

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

redoc
select id, name, phone,(select count(name) from users u1 where u1.name=u2.name) count from users u2
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!