I have a query that looks like the following:
select uid,leadcount,salescount,leadcount/salescount as diff from
(
SELECT x.uid, COUNT(*) leadcount, COUNT(DISTINCT x.fid)
FROM total_leads AS x
WHERE x.uid BETWEEN 1 AND 5
GROUP BY x.uid
) t1 left join
(
SELECT ud.UserId, COUNT(*) salescount, COUNT(DISTINCT ud.SalesID)
FROM total_sales AS ud
WHERE ud.UserId BETWEEN 1 AND 5
GROUP BY ud.UserID
) t2 on t1.uid=t2.UserId
It results in:
I'm trying to display only results where diff
is greater than 2.5
(so in this case only uid
5 should be visible on output).
I tried using WHERE diff >= 2.5
but I got "You have an error in your SQL syntax" .
Just repeat the original expression in the WHERE
clause rather than using an alias:
SELECT uid leadcount, salescount, leadcount/salescount AS diff
FROM
(
...
) t
WHERE leadcount/salescount >= 2.5;
The problem with referring to diff
in the WHERE
clause is that it is not yet available. Also, see Gordon's answer for another option, assuming you don't plan to ever aggregate. But, using HAVING
is only an option on MySQL or MariaDB.
In MySQL and MariaDB, you can just add a HAVING
clause to the end of the query:
HAVING diff >= 2.5
This acts like a WHERE
but can use the alias.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.