我的数据想要这个
Name Similar_Percentage
A 15
B 20
C 65
我想要这样
Similar_Percentage count(*)
Less than 20 2
Less than 70 1
如何为此编写查询。 我知道这样做了,但它显示的是一个数据。
答案 0 :(得分:2)
用例何时
select case when Similar_Percentage<20 then 'Less than 20'
when (Similar_Percentage<70) then 'Less than 70' end as Percentage,count(*)
from table group by case when Similar_Percentage<20 then 'Less than 20'
when (Similar_Percentage<70) then 'Less than 70' end
with cte as (
select 15 as Similar_Percentage
union all
select 20
union all
select 65
)select case when Similar_Percentage<=20 then 'Less than 20'
when (Similar_Percentage<70) then 'Less than 70' end as Percentage,count(*)
from cte group by case when Similar_Percentage<=20 then 'Less than 20'
when (Similar_Percentage<70) then 'Less than 70' end
Percentage count(*)
Less than 20 2
Less than 70 1
答案 1 :(得分:0)
另一种方法可能如下。
SELECT 'Less than 20' Percentage,
Count(*) [Count(*)]
FROM tablename
WHERE similar_percentage <= 20
UNION ALL
SELECT 'Less than 70' Percentage,
Count(*) [Count(*)]
FROM tablename
WHERE similar_percentage <= 70
AND similar_percentage > 20
答案 2 :(得分:0)
在派生表(子查询)中使用case
表达式(子查询)进行分类。 GROUP BY
其结果:
select percentage, count(*)
from
(
select case when Similar_Percentage <= 20 then 'Less than 20'
when Similar_Percentage <= 70 then 'Less than 70'
else 'More than 70'
end as percentage
from tablename
) dt
group by percentage
答案 3 :(得分:0)
MySQL允许您在group by
中使用列别名。这样可以简化查询。
我还建议使用显式的order by
,以便按所需顺序获得结果:
select (case when Similar_Percentage <= 20 then 'Less than 20'
when Similar_Percentage < 70 then 'Less than 70'
end) as Percentage,
count(*)
from cte
group by Percentage
order by min(Similar_Percentage)