Reputation: 117
Table: MyTable
[
Here is the result I desire:
For every ID in the table, count how many times that ID appears in the column Parent_ID.
Create a custom column AS Instances
to place the result.
My desired Result
I imagine to get the above result with something not more complicated than a working version of the following query:
SELECT ID, Parent_ID, COUNT( Parent_ID = ID ) AS Instances FROM MyTable
Upvotes: 1
Views: 2351
Reputation: 48770
You can use a scalar subquery to compute the extra column. For example:
select
id,
parent_id,
(
select count(*) from my_table b where b.parent_id = a.id
) as instances
from my_table a
Upvotes: 3
Reputation: 1269773
A correlated subquery is the simplest solution:
select t.*,
(select count(*) from mytable t2 where t2.parent_id = t.id) as instances
from mytable t;
Upvotes: 0