Can someone say what i do wrong in mysql? - mysql

In task below
Hackerrank
i did that query
SELECT CITY ,length(CITY ) from STATION where length(CITY )in(
select max(length(CITY ))from STATION union select min(length(CITY ))from STATION )Group by length(CITY )
order by length(CITY ) desc,CITY ;
i recieved Error
also i make another query like that
Select max(length(CITY)),CITY from STATION Group by length(CITY) Order by length(CITY)Desc;
and recieved that error
Error

The question phrases as:
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.
You don't really need aggregation to achieve this task.
I think this would be simpler expressed with union all and two row-limiting queries (one that sorts cities by ascending length, the other by descending length):
(
select city, char_length(city) cnt_chars
from station
order by char_length(city), city limit 1
) union all (
select city, char_length(city)
from station
order by char_length(city) desc, city limit 1
)
If there is only one city in the table (or if all cities have the same length), then union might be more appropriate than union all (so the same city does not appear twice in the resultset).
Alternatively, if you are running MySQL 8.0, you can use window functions:
select city, cnt_chars
from (
select s.*,
row_number() over(order by char_length(city), city) rn_asc,
row_number() over(order by char_length(city) desc, city) rn_desc
from station s
) s
where 1 in (rn_asc, rn_desc)
Side note: char_length() is safer than length(). The former counts characters, while the latter counts bytes (if your strings have multi-byte characters, this is not what you want).

You are trying to select CITY name and length(CITY) but grouping only by length(CITY). In case when two or more cities have the some value for length(CITY) mysql does not know which of the CITY should be selected.

Related

SQL Group By min(len())

select min(length(city)), city
from station
group by min(length(city));
select max(length(city)), city
from station
group by min(length(city));
output = ERROR 1056 (42000) at line 1: Can't group on 'min(length(city))'
I am trying to get minimum and maximum char length with city name. I thought this algorithm will be okay.
Why ı can't group on min(length(city))
It doesn't make sense to group by an aggregate function. Aggregate functions are called after grouping, to calculate something for all the rows in the group (such as a sum total).
You can use a subquery to calculate an aggregate for the entire table. Then you can compare this with individual rows.
SELECT city, LENGTH(city) AS length
FROM station
WHERE LENGTH(city) = (SELECT MIN(length(city)) FROM station);
Another solution :
SELECT CITY , LENGTH(city) AS length
FROM STATION
WHERE LENGTH(CITY)
IN (
SELECT MAX(LENGTH(CITY))
FROM STATION
UNION
SELECT MIN(LENGTH(CITY))
FROM STATION )

Finding Max of Max mysql

I am using a table called covid_vaccinations.
To briefly explain about the table, it tracks down all the countries' vaccination completion by every single day from Feb xx, 2020 to Jan XX, 2022.
The name of the countries are called 'location' in this table.
The countries (location) are also categorized in the column of 'continent'
To find the people who are fully vaccinated in Asia, I used the query below:
SELECT continent,location, MAX(people_fully_vaccinated)
FROM covid_vaccinations
WHERE continent LIKE '%ASIA%'
GROUP BY continent, location
ORDER BY 3 DESC;
I used MAX() since the <people_fully_vaccinated> column includes the cumulative number of data.
The query above gave me the result I wanted, see <image 1>
HERE IS MY QUESTION:
If I just want to get the GREATEST result of people_fully_vaccinated, how should I write the query?
I tried below, and it gave me the same result as <image 1>
SELECT location, MAX(peep_f_vacc_asia)
FROM (
SELECT location, MAX(people_fully_vaccinated) as peep_f_vacc_asia
FROM covid_vaccinations
WHERE continent LIKE '%ASIA%'
GROUP BY continent,location
) A
GROUP BY location
ORDER BY 2 DESC;
The desired result I want to see would be only a single row, China (which has the greatest number of people_fully_vaccinated)
Thank you so much guys...
You might be able to get away with just using a LIMIT query. A slight modification of your first query:
SELECT continent, location, MAX(people_fully_vaccinated)
FROM covid_vaccinations
WHERE continent LIKE '%ASIA%'
GROUP BY continent, location
ORDER BY 3 DESC
LIMIT 1;
But this only works in the case that there are no ties for a given continent and location for the max number of fully vaccinated. If you do have to worry about ties, and you are using MySQL 8+, then we can use RANK as follows:
WITH cte AS (
SELECT continent, location, MAX(people_fully_vaccinated) AS max_fv,
RANK() OVER (ORDER BY MAX(people_fully_vaccinated) DESC) rnk
FROM covid_vaccinations
WHERE continent LIKE '%ASIA%'
GROUP BY continent, location
)
SELECT continent, location, max_fv
FROM cte
WHERE rnk = 1;

SQL Subquery Question in MySQL. Subquery in WHERE, SELECT or FROM?

I am a beginner at SQL and I am trying to solve this question from HackerRank using Subquery. Could you tell me what I did wrong?
Problem
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.
For example, CITY has four entries: DEF, ABC, PQRS and WXY.
Sample output
ABC 3
PQRS 4
Explanation
When ordered alphabetically, the CITY names are listed as ABC, DEF, PQRS, and WXY, with lengths and . The longest name is PQRS, but there are options for shortest named city. Choose ABC, because it comes first alphabetically.
My Solution
SELECT
CITY,
LENGTH(SELECT MAX(CITY)
FROM STATION) AS Length
FROM STATION
ROWNUM 1;
SELECT
CITY, LENGTH(SELECT MIN(CITY)
FROM STATION) AS Length
FROM STATION
ROWNUM 1;
You can UNION the first and the last
CREATE tABLE A (city varchar(10))
INSERT INTO A VALUES ('DEF'),('ABC'), ('PQRS'), ('WXY')
(SELECT city
, LENGTH(city)
FROM A
ORDER BY LENGTH(city) ASC,city LIMIT 1)
UNION ALL
(SELECT city
, LENGTH(city)
FROM A
ORDER BY LENGTH(city) DESC,city LIMIT 1)
city | LENGTH(city)
:--- | -----------:
ABC | 3
PQRS | 4
db<>fiddle here
My solution without using UNION:
select city,length(city) from station order by length(city),city limit 1;
select city,length(city) from station order by length(city) desc ,city limit 1;

How to query for city name as well as length of the smallest city name from the same table

My code is this but gives error, don't know why. Please help!
select city,
min(length(city))
from station
group by length(city)=min(length(city))
order by city asc;
If you just want the city with the shortest name, you can simply order by and limit:
select city, char_length(city) city_length
from station
order by city_length
limit 1
This returns just one row. On the other hand, if you want to allow bottom ties, then you can filter with a subquery, like so:
select city, char_length(city) city_length
from station
where char_length(city) = (select min(char_length(city)) from station)

How to sum top results?

I'm wondering how one would sum the results from a query?
I want to know how many people live in total in the three biggest cities in Norway. I'm using mysql, the world.sql sample database in mysql workbench.
This is the closest I've gotten
SELECT population
FROM city
WHERE CountryCode = 'NOR'
ORDER BY population DESC
LIMIT 3
There's a few problems here namely this gives me three results instead of one, and while using LIMIT which actually limits how many results it gives, not how many it uses.
Any ideas?
You would use a subquery:
SELECT SUM(population)
FROM (SELECT population
FROM city
WHERE CountryCode = 'NOR'
ORDER BY population DESC
LIMIT 3
) cp
simply sum the result:
select sum(population) from (SELECT population
FROM city
WHERE CountryCode = 'NOR'
ORDER BY population DESC
LIMIT 3) t1
select sum(population) from (SELECT population FROM city WHERE
CountryCode = 'NOR' ORDER BY population DESC LIMIT 3) temp
Read on subqueries.
Make your current query a subquery and get sum from your subquery.
SELECT SUM(population) FROM (
SELECT population
FROM city
WHERE CountryCode = 'NOR'
ORDER BY population DESC
LIMIT 3) p
You query will now act as a virtual table, from which you can you can write a select query to get the sum