MySQL:没有分组的计数条目?

时间:2009-08-11 15:38:19

标签: sql mysql

我想提取结果并计算每个名字的数量,但没有分组......

例如我想要这个:

John Doe 3
John Doe 3
John Doe 3
Mary Jane 2
Mary Jane 2

而不是:

John Doe 3
Mary Jane 2

这有意义吗?

感谢。

6 个答案:

答案 0 :(得分:10)

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

答案 1 :(得分:3)

这使用group by,但以您想要的格式获取输出。

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

答案 2 :(得分:2)

SELECT  mo.*,
        (
        SELECT  COUNT(*)
        FROM    mytable mi
        WHERE   mi.name = mo.name
        )
FROM    mytable mo

答案 3 :(得分:2)

如果您不想使用子查询,您也可以将表连接到自身,如下所示: 这需要一个子查询。也许是这样的:

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

答案 4 :(得分:0)

SELECT `name`,
    (
        SELECT COUNT(*)
        FROM `table` AS `alt`
        WHERE `alt`.`name` = `table`.`name`
    ) AS `num`
FROM `table`

答案 5 :(得分:0)

也许算过分区?

select 
     p.name,
     count(p.name) over (partition by p.name) as counted
from some_table as p
order by counted desc