我在Hackerrank上做了这个挑战:
https://www.hackerrank.com/challenges/weather-observation-station-5
我是SQL的初学者,我尝试查询列中具有最大值的所有行,我只能通过MAX()
获取最大值。所以我试试这个:
SELECT CITY, LENGTH(CITY) AS citylength
FROM STATION
WHERE LENGTH(CITY) = (SELECT MIN(CITY) FROM STATION)
我收到错误。
我已经在google上查询了有关子查询的内容,但我并不习惯知道它究竟是如何工作的,所以我需要你的帮助。谢谢。
总而言之,我需要一个查询,可以获取通过MAX()
子句获得最大值的表上的行。
答案 0 :(得分:6)
要求您找到两种不同的结果:
这意味着您将两个不同的查询与UNION ALL粘合在一起。
(
select concat(city, ' ', length(city))
from station
order by length(city), city limit 1
)
union all
(
select concat(city, ' ', length(city))
from station
order by length(city) desc, city limit 1
);
正如Strawberry指出的那样:你需要括号来放置两个ORDER BY子句,每个查询部分一个。 (否则,您只能在整个查询的末尾放置一个ORDER BY子句。)
在您的查询中,您正在比较LENGTH(CITY)
,即一个包含名称长度的整数和MIN(CITY)
,即城市名称本身,当然无法正常工作。您必须与MIN(LENGTH(CITY))
进行比较。然后执行相同的最大值,然后使用UNION ALL。但这并不能解决LIMIT查询所带来的关系问题。
答案 1 :(得分:4)
这没有子查询
SELECT CITY, LENGTH(CITY)
FROM STATION
ORDER BY 2,1
LIMIT 1
答案 2 :(得分:2)
这有效:
SELECT CITY,LENGTH(CITY)
FROM STATION
WHERE LENGTH(CITY) = (SELECT MIN(LENGTH(CITY)) M FROM STATION);
答案 3 :(得分:1)
这可以正常工作:
select city, length(city)
from station
where length(city) = (select min(length(city)) as m from station)
order by city ASC
limit 1;
答案 4 :(得分:0)
ArrayList<Beacon> arrayList = new ArrayList<Beacon>();
String beaconName;
public void addToBeaconInfo(Beacon beacon) {
boolean beaconAlreadyInList = false;
//arrayList.add(beacon);
beaconName = "" + beacon.getId2() + "" + beacon.getId3();
//Log.i("BeaconInfo","addBeacon_beaconName: "+beaconName + " distance" + beacon.getDistance());
int i;
for(i = 0; i < arrayList.size(); i++){
Beacon tempBeacon = arrayList.get(i);
if(tempBeacon.getId2().equals(beacon.getId2())){
beaconAlreadyInList = true;
arrayList.remove(beacon);
Log.i("BeaconInfo", "addBeacon_tempBeacon: " + beacon.getId3() + " distance: " + beacon.getDistance());
break;
}
}
if(beaconAlreadyInList == false){
arrayList.add(beacon);
Log.i("arrayList","" + beacon.getDistance() + " " + beacon.getBluetoothName());
double maxDistance = beacon.getDistance();
//double a = Collections.max(maxDistance);
//Log.i("maxDistance","" + Math.max());
}
}
答案 5 :(得分:0)
select TOP 1 concat(city, ' ' , len(city)) from station where len(city) = (select min(len(city)) from station) order by city asc;
select TOP 1 concat(city, ' ' , len(city)) from station where len(city) = (select max(len(city)) from station) order by city desc;
答案 6 :(得分:0)
SELECT * FROM
(SELECT City, LENGTH(City) FROM STATION
ORDER BY LENGTH(City),city ASC)
WHERE ROWNUM <= 1
UNION ALL
SELECT * FROM
(SELECT City, LENGTH(City) FROM STATION
ORDER BY LENGTH(City) DESC)
WHERE ROWNUM <= 1;