-2

What Postgres query can I use for the below scenario?

Parent table:

enter image description here

Child table:

enter image description here

Expected result

enter image description here

Explanation:

Parent1 --> 4 equipments. Parent1 has ...

  • Child1 holding 3 equipment
  • Child2 holding 1 equipment

Parent2 --> 3 equipments. Parent2 has ...

  • Child3 holding 2 equipment
  • Child4 holding 1 equipment
1
  • 1
    Please remember to post data as text, not as image. Commented Aug 3, 2024 at 5:18

1 Answer 1

1

Basically, aggregate after joining:

SELECT p.parent AS name, count(*)
FROM   parent p
JOIN   child  c USING (name)
GROUP  BY p.parent
ORDER  BY p.parent;

Nuances of the query depend on undisclosed details.
Like, to include parents with no equipment, and optimize performance for possibly many rows per child, use a LEFT JOIN, and aggregate counts per child before the join:

SELECT p.parent AS name, sum(c.ct) AS count
FROM   parent p
LEFT   JOIN (
   SELECT c.name, count(*) AS ct
   FROM   child c
   GROUP  BY 1
   ) c USING (name)
GROUP  BY 1
ORDER  BY 1
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.