Sunday, February 19, 2012

I need help with a Query and Count

I have a pretty simple query:

Select title, avg(score) from votes group by title order by avg(score) Desc

This returns a result like this:

Abbey Road 4.0
The White Album 3.5
Meet the Beatles 3.0

The values in the score field are always 1, 2, 3, 4, or 5

What I really need from my query is 5 more columns (1, 2, 3, 4, and 5) with a count of how many votes each of those columns received. So the result set might be like this.

Abbey Road 4.0 0 0 1 1 1
The White Album 3.5 0 1 0 0 1
Meet the Beatles 3.0 2 2 2 2 2

I have tried to use the count function, but it counts all the values in the field. I can't figure out how to just count the values that match a certain criteria. When I tried to create subqueries, I got an error that said my subqueries where returning a multiple result sets.

Any suggestions would be greatly appreciated,

Chris

I found a solution using sum and case.

Chris

No comments:

Post a Comment