我正在编写一个hading子句,以检查子查询中是否包含聚合值。当我使用别名时,一切正常,但是,如果我选择不使用别名,那么hading子句将不返回任何匹配项。为了进行测试,我删除了子查询,只使用了一些数字,并在Haven子句中使用了聚合值就可以了,但是如果我使用子查询,除非使用别名,否则它是行不通的。
我有一个问题的子句是第二个(或之后)。当我使用count(challenge_id)时,它不起作用。如果我使用一些数字而不是子查询((1,2,3,4,5)中的count(challenge_id))可以正常工作,但是,如果我使用子查询,除非使用别名,否则我没有任何结果。希望我足够清楚...
select c.hacker_id, name, count(challenge_id) as chal_count from challenges as c
join hackers as h
on c.hacker_id = h.hacker_id
group by c.hacker_id,name
having
chal_count =
(select max(chal_count) from
(select count(challenge_id) as chal_count from challenges as c
join hackers as h
on c.hacker_id = h.hacker_id
group by c.hacker_id,name) as d)
or
chal_count in
(select chal_count from
(select count(challenge_id) as chal_count from challenges as c
join hackers as h
on c.hacker_id = h.hacker_id
group by c.hacker_id,name) as d
group by chal_count
having count(chal_count) = 1)
order by chal_count desc, c.hacker_id
答案 0 :(得分:0)
如果您了解SQL的操作顺序,您将知道为什么代码不起作用。 https://www.periscopedata.com/blog/sql-query-order-of-operations
HAVING
在SELECT
之前被求值,并且您将别名放在SELECT
中,因此您不能在HAVING
中使用别名。将chal_count
替换为COUNT(challenge_id)
。