gpt4 book ai didi

mysql - SQL查询: Adding Percentage

转载 作者:行者123 更新时间:2023-11-29 18:15:13 26 4
gpt4 key购买 nike

我有一个有效的查询,但除了我已有的查询之外,我想为每个类别添加一个额外的列,即免费、减少、付费和认证免费,以及与学生总数相比的百分比。谁能帮我吗?

select
count(case when Lunchstatus = 'P' then 1 else null end) as Paid
, count(case when LunchStatus = 'R' then 1 else null end) as Reduced
, count(case when LunchStatus = 'F' then 1 else null end) as Free
, count(case when LunchStatus = 'fdc' then 1 else null end) as CertifiedFree
, count(case when LunchStatus = 'P' then 1
when LunchStatus = 'fdc' then 1
when LunchStatus = 'R' then 1
when LunchStatus = 'F' then 1
else null
end) as Total
from students
where enroll_status = 0
and schoolid = %param1%

最佳答案

将现有查询视为派生表,交叉连接总计数,然后计算百分比:

select
d.*
, d.Paid * 100.0 / cj.totcount as paid_pct

... more like that

from (
select
count(case when Lunchstatus = 'P' then 1 else null end) as Paid
, count(case when LunchStatus = 'R' then 1 else null end) as Reduced
, count(case when LunchStatus = 'F' then 1 else null end) as Free
, count(case when LunchStatus = 'fdc' then 1 else null end) as CertifiedFree
, count(case when LunchStatus = 'P' then 1
when LunchStatus = 'fdc' then 1
when LunchStatus = 'R' then 1
when LunchStatus = 'F' then 1
else null
end) as Total
from students
where enroll_status = 0
and schoolid = %param1%
) d
CROSS JOIN (
select count(*) as totcount
from students
where enroll_status = 0
and schoolid = %param1%
) cj

关于mysql - SQL查询: Adding Percentage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47086443/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com