MySQL计算百分比,我可以使用变量吗?

时间:2012-11-15 15:53:28

标签: mysql variables count percentage

我有一个查询,它返回会话数量以及这些会话中的订单数量。简单的东西,但我想做的是显示订单的会话百分比。

SELECT COUNT(*) FROM table.session //Save this as variable 'Amount1'?
WHERE ses_Date BETWEEN ('2006/01/01') AND ('2011/01/01')
UNION ALL
SELECT COUNT(*) FROM table.session
WHERE Ses_ID
IN
(
SELECT Ses_ID FROM session //Save this as variable 'Amount2'?
JOIN table.order ON order.Session_ID = session.Ses_ID
WHERE ses_Date BETWEEN ('2006/01/01') AND ('2011/01/01')
GROUP by ses_ID
)

//Then do this, Display the percentage of the two
union all   
Select(SUM(amount2) /SUM(amount1) * 100)

在关于代码的评论中,我写了我想在理论上做的事情,我希望有所帮助。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

SELECT COUNT(*) / (SELECT COUNT(*) 
                   FROM table.session
                   WHERE ses_Date BETWEEN ('2006/01/01') AND ('2011/01/01')) * 100

FROM table.session
WHERE Ses_ID
IN
(
SELECT Ses_ID FROM session //Save this as variable 'Amount2'?
JOIN table.order ON order.Session_ID = session.Ses_ID
WHERE ses_Date BETWEEN ('2006/01/01') AND ('2011/01/01')
GROUP by ses_ID
)