I have a view (let's call it 'fruit') that has a column of correct answers and the associated incorrect answers from a multiple choice exam, and I would like to count which incorrect answers were chosen most frequently (the easily confused ones). The view looks something like this:
correct_answer | wrong_response
-------------------------------
apple | pear
apple | pear
apple | banana
banana | apple
banana | pear
banana | pear
banana | pear
pear | apple
And what I would like is a pivot table that counts the wrong responses respective to the correct answer, such that the columns represent the correct answer and the rows represent the counts for the wrong answers.
wrong_response | apple | banana | pear
---------------------------------------
apple | 0 | 1 | 1
banana | 1 | 0 | 0
pear | 2 | 3 | 0
I've been here before with this function, but I wasn't trying to count things that time. Any help would be much appreciated!
EDIT: For future folks, both of these solutions work! The conditional aggregation, however, is more flexible. The crosstab solution only works if you have exactly every possibility in the query. For example, if you exclude pear (or add kiwi), the crosstab solution returns an error. The conditional aggregation returns results regardless if you exclude (or add currently non-existing) records. Thanks for the help, all.