小弟在做HackerRank的題目時
遇到這題
https://www.hackerrank.com/challenges/challenges/problem
我是寫出解法了
寫法如下
select c1.hacker_id as h_id,name,count(c1.hacker_id) as cnt from Hackers h1
join Challenges c1 using(hacker_id)
group by c1.hacker_id,name
having count(c1.hacker_id)=(
select max(challenges_created)
from (
select count(hacker_id) as challenges_created
from Challenges
group by hacker_id
) g
)
union
select c2.hacker_id as h_id,name,count(c2.hacker_id) as cnt from Hackers h2
join Challenges c2 using(hacker_id)
group by c2.hacker_id,name
having cnt not in (
select challenges_created
from (
select count(hacker_id) as challenges_created
from Challenges
group by hacker_id
) g1
group by challenges_created
having count(challenges_created) > 1
)
order by cnt DESC, h_id
可是有一點我不明白
我原本卡在union的第二個query
我那裏的having 原本寫的是 count(c2.hacker_id)
但他跳出來的結果一直會是重複的值(題目要找不重複的)
所以就會錯
我不懂為什麼我把alias接在having後面就可以了
請教各位大大 是別名在having 上的差別 或是 跟count有關?
我的理解是...
當欄位使用別名的時候,是該子sql跑完到某個程度後才套用別名~~~
having剛好就在某個程度後執行
若有說錯請告知~~