-1

I have a parent table like this:

id | name
-------------
1  | item a
2  | item b

and have a chid table with a column with 2 posible types

parent id | name       | type
-------------------------------
1         | subitem a  | t1
1         | subitem b  | t1
2         | subitem c  | t2
2         | subitem d  | t1
2         | subitem e  | t2

there is a way to make a select with the following result?

parent id |  childs type t1 | childs type t2
-----------------------------------------------
1         |      2          |      0
2         |      1          |      2

any ideas? Thanks!!

1

1 Answer 1

0
SELECT c.parent_id,
       COUNT( case when c.type = 't1' then 1 end) as  `childs type t1` ,
       COUNT( case when c.type = 't2' then 1 end) as  `childs type t2`
FROM child c
GROUP BY c.parent_id

To include parents without children

SELECT p.id as parent_id,
       COUNT( case when c.type = 't1' then 1 end) as  `childs type t1` ,
       COUNT( case when c.type = 't2' then 1 end) as  `childs type t2`
FROM parent p
LEFT JOIN child c
       on p.id = c.parent_id
GROUP BY p.id
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.