【发布时间】:2020-04-18 01:45:58
【问题描述】:
对于黑客级别的 SQL 挑战,我编写了生成所需结果的 SQL 脚本。但是我过度使用了太多的子查询,我想知道代码是否可以优化。下面是 SQL 挑战的链接 https://www.hackerrank.com/challenges/challenges/problem.
简单的挑战细节:
“写一个查询来打印hacker_id、姓名和每个学生创建的挑战总数。按挑战总数降序排列你的结果。如果多个学生创建了相同的数字的挑战,然后按hacker_id对结果进行排序。如果多个学生创建了相同数量的挑战并且计数小于创建的挑战的最大数量,则将这些学生排除在结果之外。”
这是我为上述挑战编写的代码:
SELECt
h.hacker_id,
h.name,
t.tot_ch
from
hackers h,
(
Select
c.hacker_id,
count(c.challenge_id) Tot_ch
from
challenges c
Group by
hacker_id
)
T,
(
SELect
tot_ch,
count(tot_ch) DUPS
from
(
Select
c.hacker_id,
count(c.challenge_id) Tot_ch
from
challenges c
Group by
hacker_id
)
group by tot_ch
)
D
Where
h.hacker_id = t.hacker_id
And d.tot_ch = t.tot_ch
AND
(
CASe
when
d.dups < 2
then
1
ELSE
(
case when
t.tot_ch =
(
select
MAX(T1.tot_ch)
from
(
Select
c.hacker_id,
count(c.challenge_id) Tot_ch
from
challenges c
Group by
hacker_id
)
T1
)
then
1
End
)
end
)
= 1
ORDER BY
t.tot_ch desc, h.hacker_id;
【问题讨论】:
-
您应该从学习使用现代、明确、标准
JOIN语法开始。在担心子查询之前获取正确的语法。 -
查询不是脚本。
-
了解 ctes、left join、union 和 except/minus(以及用于 except/minus 的 left join idms)。 (左连接是内连接联合所有不匹配的左表行由空值扩展。)