SQL查询,如何以行方式显示结果?

时间:2015-03-31 11:18:14

标签: php mysql sql

大家好我有一个sql查询,可以查找某些范围之间的列总和。 查询在

下面

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

这样的输出

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

但我想要这样的输出

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

希望得到肯定的答复

4 个答案:

答案 0 :(得分:1)

group bycase声明一起使用:

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);

答案 1 :(得分:0)

使用此..

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

答案 2 :(得分:0)

您可以使用UNPIVOT,如下所示

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

答案 3 :(得分:0)

与之前的答案相同,只是不使用两者之间用较少的字母来制作代码:)

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;