In SQL, aliases defined in the select
clause cannot be reused in the where
clause. You need to repeat the expression (or use a subquery or cte).
MySQL has a trick that allows using aliases in the having
clause, but I would not recommend that here. You seem to want only non-negative percentages, so I think your where
clause could be simplified as:
where users_24h >= users_48h_24h
I am not sure what is the best way to phrase this in Lavarel, maybe:
->select(DB::raw('round( (users_24h - users_48h_24h) / users_48h_24h * 100,2) as daypercentage, name'))
->where(DB::raw('users_24h >= users_48h_24h'))
Note that I removed a few unnecessary parentheses in the round()
expression.