1

I want to count the same value among parent_id and id_article, but it can be 0 if there is no same value among parent_id and id_article

table:t_article
id_article      parent_id
441             0
1093            18
18              0
3141            3130
3130            0
3140            3130
3142            3130

Expected output

id_article      parent_id       Total
441             0               0
1093            18              0
18              0               1
3141            3130            0
3130            0               3
3140            3130            0
3142            3130            0

How do I make it happen?

1
  • 3
    Please edit your question to show the code you have so far. Most of us here are happy to help you improve your craft, but are less happy acting as short-order unpaid programming staff. Show us your work so far as a minimal reproducible example, the result you were expecting and the results you got, and we'll help you figure it out. It may help to re-read How to Ask. Commented Jun 6, 2018 at 8:11

1 Answer 1

1

You can get your count by doing a sub clause and then join with your main query

select a.*, coalesce(b.cnt,0)
from t_article a
left join (
  select parent_id, sum(parent_id <> 0) cnt
  from t_article 
  group by parent_id
) b on (a.id_article = b.parent_id)

Demo

Sign up to request clarification or add additional context in comments.

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.