输入格式
以下表格包含挑战数据:
黑客:hacker_id是黑客的id,而name是黑客的名字。 Hackers Table
挑战:challenge_id是挑战的ID,hacker_id是创建挑战的学生的ID。 Challenges Table
这是我写的查询
select H.hacker_id,H.name,T.challenges_created
from Hackers H join
(SELECT hacker_id ,
COUNT(Challeneges.challenge_id) as challenges_created
FROM Challenges
GROUP BY hacker_id
HAVING challenges_created >= max(challenges_created)
) T
on H.hacker_id=T.hacker_id
ORDER BY T.challenges_created desc, H.hacker_id asc
但我收到错误说
消息207,级别16,状态1,服务器WIN-ILO9GLLB9J0,第12行无效 列名'challenge_created'。消息207,级别16,状态1,服务器 WIN-ILO9GLLB9J0,第12行无效的列名称'challenge_created'。 消息4104,级别16,状态1,服务器WIN-ILO9GLLB9J0,第9行 多部分标识符“Challeneges.challenge_id”无法绑定。
答案 0 :(得分:1)
Line 9 The multi-part identifier "Challeneges.challenge_id" could not be bound.
您的拼写错误Challenges
。
答案 1 :(得分:0)
select C.Hacker_id, H.Name, count(challenge_id)
from Hackers H Inner Join Challenges C
ON H.Hacker_Id = C.Hacker_Id
group by C.Hacker_Id, H.Name
having count(challenge_id) not in (select x.ChallengeCount from (
select C.Hacker_id, H.Name, count(challenge_id) as ChallengeCount
from Hackers H Inner Join Challenges C
ON H.Hacker_Id = C.Hacker_Id
group by C.Hacker_Id, H.Name
) x
where x.ChallengeCount <> (select top 1 count(challenge_id) from Challenges group by hacker_Id order by 1 desc)
group by x.ChallengeCount
having count(x.challengecount) > 1)
order by 3 desc, 1
答案 2 :(得分:0)
SELECT c.hacker_id, h.name, COUNT(c.challenge_id) AS cnt 来自黑客 h,挑战 c 其中 h.hacker_id = c.hacker_id GROUP BY c.hacker_id, h.name 有 count(c.challenge_id) = (SELECT max(COUNT(c1.challenge_id)) FROM Challenges c1 GROUP BY c1.hacker_id) 要么 count(c.challenge_id) NOT IN (SELECT COUNT(c2.challenge_id) FROM Challenges c2 GROUP BY c2.hacker_id 有 c2.hacker_id <> c.hacker_id) ORDER BY cnt DESC, c.hacker_id;
答案 3 :(得分:-1)
通常,您不能在HAVING
子句中引用字段别名
而是使用
COUNT(Challeneges.challenge_id)
您也可以尝试
SELECT h.hacker_id,
h.name,
COUNT(c.challenge_id) AS challenge_count
FROM Hackers h
JOIN Challenges c ON c.hacker_id = h.hacker_id
GROUP BY h.hacker_id, h.name
HAVING challenge_count =
(SELECT COUNT(challenge_id) AS count_max
FROM Challenges
GROUP BY hacker_id
ORDER BY count_max DESC limit 1)
OR challenge_count IN
(SELECT DISTINCT c_compare AS c_unique
FROM (SELECT h2.hacker_id,
h2.name,
COUNT(challenge_id) AS c_compare
FROM Hackers h2
JOIN Challenges c ON c.hacker_id = h2.hacker_id
GROUP BY h2.hacker_id, h2.name) counts
GROUP BY c_compare
HAVING COUNT(c_compare) = 1)
ORDER BY challenge_count DESC, h.hacker_id;
在我的代码中,我没有使用别名,因此不会显示任何错误。