1

I have a CTE as below (logic removed)

;with cte_a as
(
    select ID, Count(AnotherID) as Counter
    from Table_A
    group by ID
)

and a user defined function that takes an Id as input and returns a table.

udf_GetRelatedItemIds(@Id)

I wanted to just count the number of related item ids returned from the user defined function for each ID in cte_a.

I was trying something like below but it didn't work

;with cte_a as
(
    select ID, Count(AnotherID) as Counter
    from Table_A
    group by ID
)
select 
ID, 
Count(select RelatedId from udf_GetRelatedItemIds(ID))
from cte_a

Please suggest a solution.

2 Answers 2

2

What about

with cte_a as
(
    select ID, Count(AnotherID) as Counter
    from Table_A
    group by ID
)
select 
a.ID, 
(SELECT COUNT(*) FROM udf_GetRelatedItemIds(a.ID)) as IntersectCount
from cte_a a
Sign up to request clarification or add additional context in comments.

Comments

0
SELECT
    T.ID,
    (SELECT COUNT(RelatedId) FROM udf_GetRelatedItemIds(T.ID)) AS cnt
FROM
    Table_A T
GROUP BY
    T.ID

WARNING!!! The performance here is likely to be horrendous as it needs to run that function once for every row in Table_A. If you can recreate your function logic in a view that gives you results for all of the IDs you'd probably be better off.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.