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