编写查询以打印hacker_id,名称以及每个学生创建的挑战总数。按降序排列挑战总数对结果进行排序。如果多个学生创建了相同数量的挑战,则按hacker_id对结果进行排序。如果多个学生创建了相同数量的挑战且计数小于创建的最大挑战数,则将结果中的学生排除在外。
我还附上了相应表格的图像
表黑客:
hacker_id name
5077 Rose
21283 Angela
62743 Frank
88255 Patrick
96196 Lisa
表挑战:
challenge_id hacker_id
61654 5077
58302 21283
40587 88255
29477 5077
1220 21283
69514 21283
46561 62743
58077 62743
18483 88255
76766 21283
52382 5077
74467 21283
33625 96196
26053 88255
42665 62743
12859 62743
70094 21283
34599 88255
54680 88255
61881 5077
所以,我做到了这一点
SELECT c.hacker_id, h.name, COUNT(c.challenge_id) AS challenge_count
FROM Challenges c LEFT JOIN Hackers h on c.hacker_id = h.hacker_id
GROUP by 1,c.hacker_id HAVING challenge_count >=
MAX(challenge_count) ORDER BY challenge_count DESC ,c.hacker_id DESC;
但没有获得预期的产出。我的输出
我需要排除输出中的重复结果,例如应排除具有相同数量挑战的黑客。
答案 0 :(得分:3)
这里有几个标准:
以下涉及项目1,2和& 3 ...
SELECT h.*
, COUNT(c.challenge_id) challenge_count
FROM hackers h
JOIN challenges c
ON c.hacker_id = h.hacker_id
GROUP
BY h.hacker_id
ORDER
BY challenge_count DESC, hacker_id;
我们可以将此查询加入到自身一次,以解决标准4,然后再次解决第5项,如下所示:
SELECT DISTINCT a.*
FROM
( SELECT h.*
, COUNT(c.challenge_id) challenge_count
FROM hackers h
JOIN challenges c
ON c.hacker_id = h.hacker_id
GROUP
BY h.hacker_id
) a
LEFT
JOIN
( SELECT h.*
, COUNT(c.challenge_id) challenge_count
FROM hackers h
JOIN challenges c
ON c.hacker_id = h.hacker_id
GROUP
BY h.hacker_id
) b
ON b.hacker_id <> a.hacker_id AND b.challenge_count = a.challenge_count
LEFT
JOIN
( SELECT h.*
, COUNT(c.challenge_id) challenge_count
FROM hackers h
JOIN challenges c
ON c.hacker_id = h.hacker_id
GROUP
BY h.hacker_id
) c
ON c.challenge_count > a.challenge_count
WHERE b.hacker_id IS NULL
OR c.hacker_id IS NULL
ORDER
BY challenge_count DESC, hacker_id;
答案 1 :(得分:2)
SELECT t1.name,
t1.hacker_id,
COALESCE(t2.challengeCount, 0) AS challengeCount
FROM Hackers t1
LEFT JOIN
(
SELECT hacker_id, COUNT(*) AS challengeCount
FROM Challenges
GROUP BY hacker_id
) t2
ON t1.hacker_id = t2.hacker_id
WHERE COALESCE(t2.challengeCount, 0) IN
(
SELECT t1.challengeCount
FROM
(
SELECT t1.hacker_id,
COALESCE(t2.challengeCount, 0) AS challengeCount
FROM Hackers t1
LEFT JOIN
(
SELECT hacker_id, COUNT(*) AS challengeCount
FROM Challenges
GROUP BY hacker_id
) t2
ON t1.hacker_id = t2.hacker_id
) t1
GROUP BY t1.challengeCount
HAVING COUNT(*) = 1
) OR COALESCE(t2.challengeCount, 0) =
(
SELECT MAX(t.challengeCount) FROM
(
SELECT COUNT(*) AS challengeCount
FROM Challenges GROUP BY hacker_id
) t
)
ORDER BY COALESCE(t2.challengeCount, 0) DESC,
t1.hacker_id