mbm*_*414 7 database sql-server data-processing
我已经开始将HackerRank上的一些编程问题作为一种"高效的分心".
我正在研究SQL部分的前几个并遇到了这个问题(链接):
Query the two cities in STATION with the shortest and
longest CITY names, as well as their respective lengths
(i.e.: number of characters in the name). If there is
more than one smallest or largest city, choose the one
that comes first when ordered alphabetically.
Input Format
The STATION table is described as follows:
Run Code Online (Sandbox Code Playgroud)
where LAT_N is the northern latitude and LONG_W is
the western longitude.
Sample Input
Let's say that CITY only has four entries:
1. DEF
2. ABC
3. PQRS
4. WXY
Sample Output
ABC 3
PQRS 4
Explanation
When ordered alphabetically, the CITY names are listed
as ABC, DEF, PQRS, and WXY, with the respective lengths
3, 3, 4 and 3. The longest-named city is obviously PQRS,
but there are options for shortest-named city; we choose
ABC, because it comes first alphabetically.
Run Code Online (Sandbox Code Playgroud)
我同意这个要求可以写得更清楚,但基本的要点很容易获得,特别是在澄清的例子中.但是,我遇到的问题是因为对该问题的评论中的说明如下:
/*
Enter your query here.
Please append a semicolon ";" at the end of the query and
enter your query in a single line to avoid error.
*/
Run Code Online (Sandbox Code Playgroud)
现在,在一行上编写查询并不一定意味着单个查询,尽管这似乎是该语句的预期目标.但是,我能够使用以下提交传递测试用例(在2行上提交,其间带有回车符):
SELECT TOP 1 CITY, LEN(CITY) FROM STATION ORDER BY LEN(CITY), CITY;
SELECT TOP 1 CITY, LEN(CITY) FROM STATION ORDER BY LEN(CITY) DESC, CITY;
Run Code Online (Sandbox Code Playgroud)
同样,这些都不是高级SQL.但它让我思考.是否有一种非常简单的方法将此输出组合到单个结果集中?我有一些想法,其中该WHERE子句基本上在OR语句中添加了一些子查询,以将两个查询合并为一个.这是我通过测试用例的另一个提交:
SELECT
CITY,
LEN(CITY)
FROM
STATION
WHERE
ID IN (SELECT TOP 1 ID FROM STATION ORDER BY LEN(CITY), CITY)
OR
ID IN (SELECT TOP 1 ID FROM STATION ORDER BY LEN(CITY) DESC, CITY)
ORDER BY
LEN(CITY), CITY;
Run Code Online (Sandbox Code Playgroud)
并且,是的,我意识到, CITY最终ORDER BY子句中的final 是多余的,但它有点说明这个查询并没有真正省去那么多努力,特别是对于单独返回查询结果.
注意:这不是真正的MAX和MIN情况.给定以下输入,您实际上并不是第一行和最后一行:
Sample Input
1. ABC
2. ABCD
3. ZYXW
Run Code Online (Sandbox Code Playgroud)
根据所写的要求,你需要#1和#2,而不是#1和#3.
这让我觉得我的解决方案实际上可能是实现这一目标的最有效方法,但我的基于集合的思维总是可以使用一些强化,而我不确定这可能会在这里发挥作用.
未经测试:
WITH CTE AS (
Select ID, len(City), row_number() over (order by City) as AlphaRN,
row_number() over (order by Len(City) desc) as LenRN) B
Select * from cte
Where AlphaRN = 1 and (lenRN = (select max(lenRN) from cte) or
lenRN = (Select min(LenRN) from cte))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
474 次 |
| 最近记录: |