0

I have the following database which shows characteristics of attributes as follows:

attributeId | attributeCode | groupCode
------------+---------------+-----------
1           | 10            | 50
1           | 10            | 50
1           | 12            | 50

My desired result from a select would be:

attributeId | groupcount | code10 | code12
------------+------------+--------+--------
1           | 1          | 2      | 1

Which means: attributeId = 1 has only one groupCode (50), where attributeCode=10 occurs 2 times and attributeCode=12 occurs 1 time.

Of course the following is not valid, but you get the idea of what I'm trying to achieve:

select attributeId,
       count(distinct(groupCode)) as groupcount,
       attributeCode = 10 as code10, 
       attributeCode = 12 as code12
from table
group by attributeId;

1 Answer 1

2

Try this:

SELECT attributeId, COUNT(DISTINCT groupCode) AS groupcount,
       COUNT(CASE WHEN attributeCode = 10 THEN 1 END) AS code10,
       COUNT(CASE WHEN attributeCode = 12 THEN 1 END) AS code12
FROM mytable
GROUP BY attributeId

Demo here

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

2 Comments

That's interesting. Do you think it matters if I use COUNT or SUM(..) (both work and produce the same results)?
@membersound It should return the same result. I personally find COUNT more suitable because it expresses what you really want to do in this case: count the number of either 10 or 12 value occurrences.

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.