计算单独字段中具有匹配值的记录数

时间:2013-06-26 01:25:00

标签: sql count

我有一张桌子(myTable):

id  | name  | orig_id
----+-------+--------
01  | Bill  | -
02  | Tom   | 01
03  | Sam   | 01
04  | Alex  | 02
05  | Phil  | -
06  | Bob   | 01

我想要一个返回每条记录的查询,但是添加了一列,其中包含orig_id等于当前行id的其他行的计数。

结果表格如下所示:

id  | name  | orig_id | mycount
----+-------+---------+--------
01  | Bill  | -       | 3
02  | Tom   | 01      | 1
03  | Sam   | 01      | 0
04  | Alex  | 02      | 0
05  | Phil  | -       | 0
06  | Bob   | 01      | 0

我尝试了以下查询,但没有得到任何结果:

SELECT *, COUNT(t.name) AS mycount
FROM "myTable" AS t
WHERE t.id=t.orig_id
GROUP BY t.id;

如何达到预期效果?

2 个答案:

答案 0 :(得分:5)

您可以通过加入和聚合来执行此操作:

SELECT t.*, tsum.mycount 
FROM myTable t join
     (select orig_id, count(name) as mycount
      from myTable
      group by orig_id
     ) tsum
     on t.id = tsum.orig_id;

答案 1 :(得分:0)

带有计数的简单left join会执行此操作:

select t.id, t.name, t.orig_id, count(o.id) mycount 
from myTable t
left join myTable o on t.id = o.orig_id
group by t.id, t.name, t.orig_id

查看产生此结果的live demo on SQLFiddle

ID  NAME    ORIG_ID MYCOUNTÂ 
01  Bill    (null)  3
02  Tom     01      1
03  Sam     01      0
04  Alex    02      0
05  Phil    (null)  0
06  Bob     01      0