【问题标题】:2 result perecentage with the same table2 结果百分比与同一张表
【发布时间】:2021-04-16 14:27:57
【问题描述】:
select AGE,
(count (case when age > 22 then name end)*100.0/count(name)) as percentage
from student;

结果 20 30.0

select name, age,
(select 100*age/sum(age) over () as percentage from student) as percentage ,
(count(case when age > 22 then name end )*100.0/ count (name)) as Total_Perecentage 
from student
WHERE age > 22
GROUP BY 1,2;

结果

Elis    27  9   100.0
Mice    23  9   100.0
Sara    25  9   100.0

我的问题如何将 Total_percentage 从 100% 更新为 30%(所有结果都在一个表中)作为第一个查询

简单来说,30%是10个学生中超过22个的3个名字的总百分比。

Result

【问题讨论】:

    标签: sqlite group-by subquery percentage case-when


    【解决方案1】:

    使用有条件地在表上聚合的子查询更容易:

    SELECT name, age, 
           (SELECT 100 * AVG(age > 22) FROM student) AS Total_Perecentage 
    FROM student 
    WHERE age > 22
    

    请参阅demo
    结果:

    name age Total_Perecentage
    Sara 25 30
    Mice 23 30
    Elis 27 30

    【讨论】:

      猜你喜欢
      • 2011-05-25
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-20
      • 1970-01-01
      相关资源
      最近更新 更多