Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql - reusing calculated values

I don't know exactly how to word this question but here it is. I want to reuse values that i calculated in my query to calculate another value. Variables is the correct word i guess. here is my query:

SELECT 
    t1.label as label,SUM(t1.totalEvents) as Entry,SUM(t2.totalEvents) as Back,  
    ROUND(Entry/Back*100,2) as 'Rate'
FROM 
    trackReports_daily t1
.... rest of query ...

Inside round i want to to use the value returned by SUM(t1.totalEvents), but when i use Entry i get this error Unknown column 'Entry' in 'field list'

How else can i get the value in there without recalculating everytime like this:

ROUND(SUM(t2.totalEvents)/SUM(t1.totalEvents)*100,2)
like image 660
Ibu Avatar asked Jun 15 '11 19:06

Ibu


3 Answers

Take a look at this example

select (select @t1:=sum(field1)),(select @t2:=sum(field2)),@t1/@t2 from table
like image 170
Nicola Cossu Avatar answered Oct 21 '22 03:10

Nicola Cossu


You could use a subquery:

SELECT label, Entry, Back, ROUND(Entry/Back*100,2) as 'Rate'
FROM (
    SELECT SUM(t1.totalEvents) as Entry, SUM(t2.totalEvents) as Back, t1.label as label
    FROM trackReports_daily t1 
    .... rest of query ... 
) as temp;
like image 6
AJ. Avatar answered Oct 21 '22 03:10

AJ.


One option would be to use a subquery in the FROM clause like:

SELECT 
    t1.label as label,SUM(t1.totalEvents) as Entry,t2.Back,  
    ROUND(t1.Entry/t2.Back*100,2) as 'Rate'
FROM 
    (SELECT *, SUM(totalEvents) as Entry FROM trackReports_daily) t1
    (SELECT *, SUM(totalEvents) as Back FROM someTable) t2
.... rest of query ...

If you want to reuse Rate in further queries then it will get complicated, and I do not know if this will have optimal performance, but I think it will do what you asked for in your example.

like image 1
murgatroid99 Avatar answered Oct 21 '22 03:10

murgatroid99