我有这样一个表(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;
我怎样才能达到预期的效果?
您可以通过联接和聚合来做到这一点:
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;