MySQL: Count entries without grouping?

前端 未结 6 988
予麋鹿
予麋鹿 2021-02-07 06:32

I want to pull results and count how many of each name is pulled but without grouping...

for example I want this:

John Doe 3
John Doe 3
John Doe 3
Mary J         


        
相关标签:
6条回答
  • 2021-02-07 06:48
    SELECT `name`,
        (
            SELECT COUNT(*)
            FROM `table` AS `alt`
            WHERE `alt`.`name` = `table`.`name`
        ) AS `num`
    FROM `table`
    
    0 讨论(0)
  • 2021-02-07 06:54
    SELECT  mo.*,
            (
            SELECT  COUNT(*)
            FROM    mytable mi
            WHERE   mi.name = mo.name
            )
    FROM    mytable mo
    
    0 讨论(0)
  • 2021-02-07 07:02

    This uses group by but gets the output in the format you want.

    SELECT Name, NG.NameCount
    FROM Names
    INNER JOIN
        (SELECT Name, Count(1) As NameCount
        FROM Names
        GROUP BY Name) NG
    ON Names.Name = NG.Name
    
    0 讨论(0)
  • 2021-02-07 07:02

    Maybe count over partition?

    select 
         p.name,
         count(p.name) over (partition by p.name) as counted
    from some_table as p
    order by counted desc
    
    0 讨论(0)
  • 2021-02-07 07:06
    SELECT b.name, a.the_count
    FROM
      some_table b, 
      (SELECT name, COUNT(*) AS the_count
      FROM some_table
      GROUP BY name) AS a
    WHERE b.name = a.name
    
    0 讨论(0)
  • 2021-02-07 07:06

    If you don't want to use a subquery, you can also join the table to itself like so: That would require a subquery. Perhaps something like this:

    SELECT t1.name, COUNT(t2.name)
    FROM my_table AS t1
    INNER JOIN my_table AS t2 ON (t1.primary_key_field = t2.primary_key_field)
    WHERE some_conditions
    GROUP BY t1.name
    
    0 讨论(0)
提交回复
热议问题