表:MyTable
这是我想要的结果:
对于表中的每个ID,计算该ID在列parent_id中出现的次数。 创建一个自定义列作为instances
来放置结果。
我想要的结果
我想用不比以下查询的工作版本更复杂的东西来得到上面的结果:
SELECT ID, Parent_ID, COUNT( Parent_ID = ID ) AS Instances FROM MyTable
相关子查询是最简单的解决方案:
select t.*,
(select count(*) from mytable t2 where t2.parent_id = t.id) as instances
from mytable t;
您可以使用标量子查询来计算额外的列。 例如:
select
id,
parent_id,
(
select count(*) from my_table b where b.parent_id = a.id
) as instances
from my_table a