我正在练习关于HackerRank的SQL知识,我写了一个查询,我觉得它不应该嵌套但我不知道如何优化它:
SELECT
CAST(LONG_W as numeric(16, 4))
FROM
STATION
WHERE
LAT_N = (SELECT MIN(LAT_N)
FROM STATION
WHERE LAT_N > 38.7780)
它的黑客天气观测站17号。任何人都可以帮忙解决这个问题吗?
编辑:这是来自HackerRank:
给定一个表STATION,其中包含五列ID,CITY,STATE,NORTHERN LATITUDE和WESTERN LONGITUDE的数据。
+-------------+------------+
| Field | Type |
+-------------+------------+
| ID | INTEGER |
| CITY | VARCHAR(21)|
| STATE | VARCHAR(2) |
| LAT_N | NUMERIC |
| LONG_W | NUMERIC |
+-------------+------------+
写一个查询,找到相应的Western Longitude到北纬度的最小值,大于38.7780,最多4位小数。
答案 0 :(得分:1)
如果您只期望一个最低记录
,请尝试此操作SELECT top 1 cast(LONG_W as numeric(16, 4)) FROM STATION
WHERE LAT_N > 38.7780 order by LAT_N asc
答案 1 :(得分:0)
也许这个?
DECLARE @lat INT;
SELECT @lat=MIN(LAT_N) FROM STATION WHERE LAT_N > 38.7780
SELECT cast(LONG_W as numeric(16, 4)) FROM STATION
WHERE LAT_N = @lat
或者
SELECT cast(a.LONG_W as numeric(16, 4))
FROM STATION a
INNER JOIN (SELECT MIN(LAT_N) LAT_N FROM STATION WHERE LAT_N > 38.7780) b
ON a.LAT_N = b.LAT_N