这是我的疑问:
在一个查询中有很多来自求和的结果,这些求和想要得到它们中的百分比,所以我想分配一个变量,这个解决方案一试,因为我无法添加别名,我想补充一下 2 AS a,1 AS b形式a + b AS结果...相同的查询标题
Select a.*, SUM( a.val1 ) AS val1, SUM( b.val2 ) AS val2
from quest1 a , quest2 b
我想这样做:
Select a.*, @N:= SUM( a.val1 ) AS val1, @M:= SUM( b.val2 ) AS val2,
(100*@N/@M) as percent
from quest1 a , quest b
答案 0 :(得分:1)
您可以通过执行不带变量的子选择来实现此目的
SELECT t.*,
(100 * (t.val1/t.val2)) `percent`
FROM
(
Select a.*,SUM( a.val1 ) AS val1,
SUM( b.val2 ) AS val2
from quest1 a , quest b
) t
或
Select a.*,
SUM( a.val1 ) AS val1,
SUM( b.val2 ) AS val2,
(100 * ( SUM( b.val1 ) / SUM( b.val2 ) ) ) `percent`
FROM quest1 a , quest b
注意使用不带group by子句的聚合函数将导致单行