现在我还在练习sql。并试图解决hackkerank上的挑战,但我有一些问题和问题
我接受的挑战是:
《港口》
链接:https://www.hackerrank.com/challenges/the-pads/problem?isFullScreen=true
这个挑战包含根据他们的职位来计算人数,目标是将人数从最小到最大排序,然后对职业进行alfabeticaly排序。
问题:
我试图通过使用ORDER BY
来解决这个问题,但它似乎并不影响对输出的排序
查询:
(Select concat(name,'(',LEFT(Occupation,1),')') as name from occupations) union
(select concat('There are a total of ', count(*),' ', lower(occupation), 's.')
from occupations group by occupation order by count(*) asc, occupation asc)
输出:
Ashley(P)
Samantha(A)
Julia(D)
Britney(P)
Maria(P)
Meera(P)
Priya(D)
Priyanka(P)
Jennifer(A)
Ketty(A)
Belvet(P)
Naomi(P)
Jane(S)
Jenny(S)
Kristeen(S)
Christeen(S)
Eve(A)
Aamina(D)
There are a total of 7 professors.
There are a total of 4 actors.
There are a total of 3 doctors.
There are a total of 4 singers.
预期输出:
Aamina(D)
Ashley(P)
Belvet(P)
Britney(P)
Christeen(S)
Eve(A)
Jane(S)
Jennifer(A)
Jenny(S)
Julia(D)
Ketty(A)
Kristeen(S)
Maria(P)
Meera(P)
Naomi(P)
Priya(D)
Priyanka(P)
Samantha(A)
There are a total of 3 doctors.
There are a total of 4 actors.
There are a total of 4 singers.
There are a total of 7 professors.
问题:
1.为什么我的查询在hackkerank上不起作用?我在w3school操场上尝试了类似的方法,似乎工作正常。
链接操场w3school:https://www.w3schools.com/sql/trysqlserver.asp?filename=trysql_func_sqlserver_concat
我在w3school上尝试的查询:
SELECT concat(count(*), ' ',country)
from customers
group by country
ORDER BY count(*) asc
1.我试着使用某人的解决方案,它的工作,但我不明白为什么
(Select concat(name,'(',LEFT(Occupation,1),')') as name from occupations ) union
( select concat("There are a total of ", count(Occupation)," ",lower(Occupation),"s.")
from Occupations group by Occupation order by count(Occupation) ) ORDER BY name
- 当我删除
order by count(Occupation)
查询仍然工作,为什么? - 为什么使用
ORDER BY name
而不是`order by count(*)?
我将感谢任何解释。
2条答案
按热度按时间kq0g1dla1#
按要求订购2套的并集
apeeds0o2#
让我们拆分查询:
不能使用group by对它们执行
UNION
操作,否则整个查询将失败,但可以在UNION
之后执行ORDER BY
操作,并且应该得到预期的结果,或者至少我是通过在sqlite构建上运行以下代码得到的