我有一个如下查询:
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
结果为:
我尝试仅显示diff
大于2.5
的结果(因此在这种情况下,只有uid
5 在输出中可见) 。
我尝试使用WHERE diff >= 2.5
,但收到“您的SQL语法有错误” 。
答案 0 :(得分:2)
只需在WHERE
子句中重复原始表达式,而不使用别名:
SELECT uid leadcount, salescount, leadcount/salescount AS diff
FROM
(
...
) t
WHERE leadcount/salescount >= 2.5;
在diff
子句中引用WHERE
的问题是尚不可用。另外,假设您不打算进行汇总,请参阅戈登的答案以获取其他选择。但是,仅在MySQL或MariaDB上使用HAVING
。
答案 1 :(得分:1)
在MySQL和MariaDB中,您只需在查询的末尾添加一个packages.config
子句:
HAVING
这类似于HAVING diff >= 2.5
,但可以使用别名。