我有以下两个返回计数结果的MySQL语句
第一句话:
SELECT count(*) as total FROM sessions ap JOIN session_codes codes USING (code_id) WHERE ap.user=>100 AND (ap.session_date BETWEEN '2017-01-15' AND '2017-05-10') AND codes.status>=1
第二声明:
SELECT count(*) as total_sessions FROM sessions WHERE (session_date BETWEEN '2017-01-15' AND '2017-05-10') AND user=>100
是否有人知道我可以将第一个陈述的结果除以第二个陈述的结果并将其乘以100得到一个舍入百分比?
我刚刚尝试了以下内容,它似乎有效,但不确定这是否会以最快的方式返回结果,因为它需要大约0.5秒来完成任务:
SELECT (
(SELECT count(*) as total FROM sessions ap JOIN session_codes codes USING (code_id) WHERE ap.user=>100 AND (ap.session_date BETWEEN '2017-01-15' AND '2017-05-10') AND codes.status>=1) /
(SELECT count(*) as total_sessions FROM sessions WHERE (session_date BETWEEN '2017-01-15' AND '2017-05-10') AND user=>100)
) * 100 AS percentage
答案 0 :(得分:0)
将变量设置为query
结果,并在执行查询后选择它。检查一下
SET @result_1 = (SELECT count(*) as total FROM sessions ap JOIN session_codes codes USING (code_id) WHERE ap.user=>100 AND (ap.session_date BETWEEN '2017-01-15' AND '2017-05-10') AND codes.status>=1 );
SET @result_2 = (SELECT count(*) as total_sessions FROM sessions WHERE (session_date BETWEEN '2017-01-15' AND '2017-05-10') AND user=>100 );
select (@result_1 / @result_2) * 100