0

I have a table for user input to questions. They were given the option to give up to five answers to the same question so you have 5 fields with up to five different answers for the same question.

So field1,filed2,field3,field4,field5 could all have the answer "foo"

I want create a query that will return a number count of the total answers in any of the five columns for all users for each possible answer.

So the output would be:

'foo' 22 'I like cake' 32 'who cares' 2

I am on the right track with the following but I suspect there is a more elegant solution. Here is what I have so far:

SELECT field1,filed2,field3,field4,field5,
         (sum(CASE WHEN field1='foo' THEN 1 ELSE 0 END) +
         sum(CASE WHEN field2='foo' THEN 1 ELSE 0 END)) +
         sum(CASE WHEN field3='foo' THEN 1 ELSE 0 END)) +
         sum(CASE WHEN field4='foo' THEN 1 ELSE 0 END)) +
         sum(CASE WHEN field5='foo' THEN 1 ELSE 0 END)) AS count

   FROM items
   GROUP BY field1,filed2,field3,field4,field5
  ;

Any suggestions would be appreciated.

2
  • If you get the desired result this query is just fine! Commented Sep 30, 2016 at 12:18
  • Add some sample table data, and the expected result. (As well formatted text.) Commented Sep 30, 2016 at 12:23

1 Answer 1

1

Perhaps this is what you need. Have a derived table that returns all columns UNION ALL-ed into one. Then do the GROUP BY:

select field, count(*)
from
(
    select field1 as field from items
    union all
    select field2 from items
    union all
    ...
    select fieldn from items
) dt
group by field
Sign up to request clarification or add additional context in comments.

3 Comments

Need to add where condition as well for each selection of 'foo'.
Interesting. I will incorporate this and see what I get. Looks close.
@Suraz, wasn't that just an example? If needed, add a WHERE clause just before the GROUP BY.

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.