Question

this is my query:

in a query have many results that come from summations, these summations want to get the percentage among them, so I want to assign a variable, this solution a try since I can not add up the alias, I would like to add 2 AS a, 1 AS b of the form a + b AS result ... Same query header

Select a.*, SUM( a.val1 ) AS val1, SUM( b.val2 ) AS val2
from quest1 a , quest2 b

I want to do this:

Select a.*, @N:= SUM( a.val1 ) AS val1,  @M:= SUM( b.val2 ) AS val2,
(100*@N/@M) as percent
from quest1 a , quest b
Was it helpful?

Solution

You can achieve this by doing a subselect without variables

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

or

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

Note using aggregate functions without group by clause will result in a single row

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top