计算重复的字段值

时间:2013-10-04 19:58:47

标签: mysql sql database subquery

我需要计算某个字段的值出现的次数,[i]喜欢[/ i]:

Name    | Age | HowManyTimesTheNameRepeat  

Ghaleon | 21  | 3  
Ghaleon | 21  | 3  
Ghaleon | 21  | 3  
Bianca  | 20  | 2    
Bianca  | 20  | 2  
Carla   | 25  | 1

编辑

我想我把事情弄糊涂了。这是我的代码:

SELECT t1.matricula AS Matricula, t1.descricao_debito AS Descricao, t1.quantidade AS Qtd,(SELECT COUNT(t2.name) FROM table1 AS t2 WHERE t1.name= t2.name) As MesmoNome
FROM table1 AS t1 INNER JOIN table2 AS t2 ON t1.dados_bancarios = t2.codigo
WHERE t1.dados_bancarios > 0 AND t1.configuracao =  2 AND t1.remessa = 116
GROUP BY t1.nome_titular
HAVING COUNT(*) > 0

这就是我的尝试,所以这就是我真正需要的东西:

我需要知道相同名称重复多少次,但我不能使用group by,因为我需要接收每个结果行。此外,我的 InnerJoin 不会通过 name 字段发生。
可能吗?

5 个答案:

答案 0 :(得分:2)

我只能快速访问SQLite 3,但我认为这也适用于MySQL:

SELECT
    p1.Name,
    p1.Age,
    (SELECT count(p2.Name) FROM person AS p2 WHERE p1.Name == p2.Name) as QtdName
FROM person AS p1

答案 1 :(得分:2)

某些答案会产生正确的结果,但是,出于某种原因,每个答案都使用子查询。

随着桌子的增长,这会变得很昂贵!

这是另一种方法:

SELECT * 
 FROM test t 
 NATURAL JOIN 
 (SELECT name, count(name) FROM test GROUP BY name) AS t2;

这样,名称计数的查询不会在表中的每一行执行,而只会执行一次。

这是an SQLFiddle来说明这会如何影响效果。我创建了一个简单的模式,并用190行填充了表。我鼓励你看一下执行计划。即使对于像这样的小数据集,差异也是显而易见的。带子查询的版本执行时间大约要长10倍。

答案 2 :(得分:1)

SELECT name, Count(name) As QtdName from table group by name

修改

SELECT name,Count(name)作为表中的QtdName,其名称如“%somename%”;

答案 3 :(得分:1)

SELECT t.name, 
(
  SELECT Count(s.name) As TempCount 
  FROM TableName as s 
  WHERE s.name = t.name 
) AS QtdName
FROM TableName as t

将所有出现的TableName替换为表的实际名称。

答案 4 :(得分:1)

SELECT name, Count(name) As QtdName 
FROM table 
GROUP BY name