求助,MySQL想得到百分比,能帮忙看看哪里出问题喇嘛


select *, count(1) as allcount,sum(case when y_n='y' then 1 else 0 end) as ycount,sum(case when y_n='n' then 1 else 0 end) as ncount,CONCAT(ROUND(yconut/allcount*100,2),'%')

from yh_type;

去掉CONCAT(ROUND(yconut/allcount*100,2),'%')这块是能正常查询的

TIM截图20190603165320.png

Guard 发布于 2019-6-3 16:54
1min目标场景问卷 立即参与
回答问题
悬赏:4 F币 + 添加悬赏
提示:增加悬赏、完善问题、追问等操作,可使您的问题被置顶,并向所有关注者发送通知
共5回答
最佳回答
0
zsh331Lv8专家互助
发布于2019-6-3 16:59
SELECT
	*, count(1) AS allcount,
	sum(CASE WHEN y_n = 'y' THEN 1 ELSE 0 END) AS ycount,
	sum(CASE WHEN y_n = 'n' THEN 1 ELSE 0 END) AS ncount,
CONCAT(
	ROUND(
		sum(CASE WHEN y_n = 'y' THEN 1 ELSE 0 END) / count(1) * 100,
		2
	),
	'%'
)
FROM
	yh_type;


最佳回答
0
虾米、木木Lv2初级互助
发布于2019-6-3 16:59


select *, count(1) as allcount,sum(case when y_n='y' then 1 else 0 end) as ycount,sum(case when y_n='n' then 1 else 0 end) as ncount,CONCAT(ROUND(sum(case when y_n='y' then 1 else 0 end)/sum(case when y_n='n' then 1 else 0 end)*100,2),'%')

from yh_type;

ycount 和ncount并不存在表中 一种方法是如上所示,一种方法是

select *,,CONCAT(ROUND(yconut/allcount*100,2),'%')  from(select *, count(1) as allcount,sum(case when y_n='y' then 1 else 0 end) as ycount,sum(case when y_n='n' then 1 else 0 end) as ncount

from yh_type)


最佳回答
0
风云无忌Lv0见习互助
发布于2019-6-3 17:00


with t1 as (

select *, count(1) as allcount,sum(case when y_n='y' then 1 else 0 end) as ycount,sum(case when y_n='n' then 1 else 0 end) as ncount

from yh_type)

select ycount,ncount, CONCAT(ROUND(yconut/allcount*100,2),'%') from t1


最佳回答
0
firegunzxLv6高级互助
发布于2019-6-3 17:01

在同一级查询里不能直接用as 后面的重命名作为字段名,要么把yconut替换成sum(case when y_n='y' then 1 else 0 end) ,要么在外面加一层查询。-

最佳回答
0
张洪威Lv6高级互助
发布于2019-6-3 17:01

你别用别名,直接把前面计算的式子放到里面。


CONCAT(ROUND(sum(case when y_n='y' then 1 else 0 end)/count(1)*100,2),'%')


或者在上面嵌套一个。

select aa.* , CONCAT(ROUND(aa.yconut/aa.allcount*100,2),'%') from

(select *, count(1) as allcount,sum(case when y_n='y' then 1 else 0 end) as ycount,sum(case when y_n='n' then 1 else 0 end) as ncount

from yh_type) aa



  • 6关注人数
  • 390浏览人数
  • 最后回答于:2019-6-3 17:01
    请选择关闭问题的原因
    确定 取消
    返回顶部