0

Hello guys I have a sql query that finds sum of columns between some ranges. The query is below

select sum(case when rating_value between 0 and 1.9 then 1 end) as Poor, sum(case when rating_value between 2 and 2.9 then 1 end) as Average, sum(case when rating_value between 3 and 3.9 then 1 end) as Good, sum(case when rating_value between 4 and 5 then 1 end) as Very_Good from rating

which outputs like this

poor | good | verygood | average 39 | 131 | 231 | 552

But i want output like this

Rating |  Count or Value
-----------------------
Poor        31
Good        21
Average     552
very good   231

Hoping for a positive reply

4 Answers 4

1

Use group by with a case statement:

select (case when rating_value between 0 and 1.9 then 'Poor'
             when rating_value between 2 and 2.9 then 'Average'
             when rating_value between 3 and 3.9 then 'Good'
             when rating_value between 4 and 5 then 'Very_Good'
        end) as grp, count(*)
from rating
group by grp
order by min(rating_value);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank .. Gordon it worked. Sorry cant vote up for this answer bcoz i dont have much reputation.
0

Use this..

select 
(case when rating_value between 0 and 1.9 then 'Poor' 
case when rating_value between 2 and 2.9 then  'Average'
case when rating_value between 3 and 3.9 then 'Good'
case when rating_value between 4 and 5 then 'Very_Good'
end) as rate, count(*) AS cnt
from rating
group by rate
order by cnt

Comments

0

You can use UNPIVOT as below

SELECT Rating,Value FROM(

select 10  as Poor,20 as Average,45 as Good,15 as Very_Good /*Your Query*/

) AA
UNPIVOT
(Value FOR Rating IN ([Poor],[Average],[Good],[Very_Good])) BB

Comments

0

The same as previous answers, just not using between to make the code with less letters :)

SELECT
    ( CASE WHEN rating_value < 2 THEN 'Poor'
           WHEN rating_value < 3 THEN 'Average'
           WHEN rating_value < 4 THEN 'Good'
           WHEN rating_value <= 5 THEN 'Very_Good'
      END ) AS rate ,
    COUNT(*)
FROM
    rating
GROUP BY
    grp
ORDER BY
    1;

Comments

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.