0

I have following database table:

id, owner_id, partner_id, level
1, 121, 234, gold
2, 121, 342, silver
3, 121, 423, silver
4, 233, 333, silver
5, 233, 434, gold

I am trying to get result in following format:

owner_id, number_of_partners, total_gold, total_silver, total_bronze

I am not sure if this is possible to do, I so far I started with the basic group by query where I get the total partners per owner.

SELECT owner_id, count(partner_id) FROM owner_partner GROUP BY owner_id

How can I extend this to get my results?

2 Answers 2

1

Just use conditional aggregation:

SELECT owner_id, count(partner_id),
       sum(case when level = 'gold' then 1 else 0 end) as gold,
       sum(case when level = 'silver' then 1 else 0 end) as silver,
       sum(case when level = 'bronze' then 1 else 0 end) as bronze
FROM owner_partner
GROUP BY owner_id;
Sign up to request clarification or add additional context in comments.

Comments

1

I suggest shorter syntax (about same performance as CASE statements):

SELECT owner_id
     , count(*) AS total
     , count(level = 'gold' OR NULL) AS gold
     , count(level = 'silver' OR NULL) AS silver
     , count(level = 'bronze' OR NULL) AS bronze
FROM   tbl
GROUP  BY 1;

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.