-2

我需要计算某个字段的值出现了多少次,[i]like[/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发生。
可能吗?

4

5 回答 5

2

I only had quick access to SQLite 3 but I assume this should work in MySQL just as well:

SELECT
    p1.Name,
    p1.Age,
    (SELECT count(p2.Name) FROM person AS p2 WHERE p1.Name == p2.Name) as QtdName
FROM person AS p1
于 2013-10-04T20:19:05.640 回答
2

一些答案产生了正确的结果,但是,由于某种原因,它们中的每一个都使用了一个子查询。

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

这是执行此操作的另一种方法:

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

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

这是一个 SQLFiddle来展示这如何影响性能。我创建了一个简单的模式并在表中填充了 190 行。我鼓励你看看执行计划。即使对于像这样的小数据集,差异也很明显。带有子查询的版本需要大约 10 倍的时间来执行。

于 2013-10-04T20:54:33.000 回答
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 替换为您的表的实际名称。

于 2013-10-04T20:02:08.257 回答
1
SELECT name, Count(name) As QtdName 
FROM table 
GROUP BY name 
于 2013-10-04T20:02:56.427 回答
1
SELECT name, Count(name) As QtdName from table group by name

编辑

SELECT name, Count(name) As QtdName from table where name like "%somename%";

于 2013-10-04T20:00:38.957 回答