Skip to content
Advertisement

Counting values within the same row in SQL Server

My SQL Server problem is as follows: let’s say we have clients and we wish to rate them based on 4 categories (Score_1…Score_4) on a scale of 0 to 2. I have a table presented below:

Database

What I want my code to do is count the number of 0, 1, and 2 values each of my clients recieved. The result table I would like to get would like this:

Desired result

So client_1 got two 0 scores, one 1 score and one 2 score, client_2 got one 0 score, one 1 score and two 2 scores. Any suggestions? Thanks in advance!

Advertisement

Answer

You can unpivot, then do conditional aggregation:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement