find maximum count in sql - mysql

I have a table containing a sample data of covid variant cases
country covid_variant cases
USA SARS Covid 2000
USA Delta 100
USA Omicron 500
Mexico SARS Covid 2000
USA Omicron 400
How can I get the data based on max cases of each variant?
covid_variant countries max_cases
SARS Covid USA 2000
SARS Covid Mexico 2000
Delta USA 100
Omicron USA 500

Using ROW_NUMBER:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY covid_variant, country
ORDER BY cases DESC) rn
FROM yourTable
)
SELECT covid_variant, country, cases
FROM cte
WHERE rn = 1;

Supposing this is MSSQL, with TSQL syntax, one possible answer is:
select covid_variant, country, MAX(cases) as max_cases
from [tablename]
group by covid_variant, country
order by covid_variant, country

If your using MySQL 5.7 try using MAX and GROUP BY.
SELECT covid_variant,
country,
MAX(cases) AS max_cases
FROM your_table
GROUP BY covid_variant, country
ORDER BY max_cases DESC, country DESC;
RESULT
covid_variant country max_cases
------------- ------- -----------
SARS Covid USA 2000
SARS Covid Mexico 2000
Omicron USA 500
Delta USA 100

Related

How do I write SQL query for average?

I have recently attended an interview on SQL. Below is the question:
Write a query to retrieve city name, state name, city population and return the following calculations along with the before mentioned fields.
Average city population in the state.
Difference between the city population and average city population in that state.
City Table:
City_Name
State_NAme
Population
Baltimore
Maryland
30000
College Park
Maryland
18000
Columbia
Maryland
20000
Boston
Massachusetts
35000
Malden
Massachusetts
10000
Dover
Delaware
20000
Jersey City
New Jersey
35000
I have tried below query but I didnot get desired output. Can anyone help me with correct query?
select * from city_table;
select state_name, sum(population)/count(city_name) as average_city_pop
from city_table
group by state_name;
You need to explore sql more, learn about aggregation functions and joins. Your query is correct in obtaining the average population. You need to join it to the original table to get your result.
with avg_city_pop as (select state_name, avg(population) as avg from city group by state_name)
select c.*, acp.avg as average_city_population, abs(acp.avg-c.population) as difference from city c inner join avg_city_pop acp on c.state_name = acp.state_name;
try it out here
For MySQL versions before 8.0, we can use a correlated subquery to get the average population for each state, which can alss be used to calculate the gap between city population and state average population. Note, the abs function is optionally used to always return a positive number. Omit it if necessary.
select city_name,state_name,(select avg(population) from city where state_name=c.state_name group by state_name ) as average_pop ,
abs(population - (select avg(population) from city where state_name=c.state_name group by state_name )) as gap_pop
from city c;
select
city_name,
state_name,
population,
avg(population) over (partition by state_name) as Avg_pop,
population-avg(population) over (partition by state_name) as Difference
from city;
see sqlfilldle: https://www.db-fiddle.com/f/tVxdH6bQvsu48umWgLmrQB/0
This needs MySQL 8.0+, because over_clause is available since 8.0.
output:
city_name
state_name
population
Avg_pop
Difference
dover
delaware
20000
20000.0000
0.0000
baltimore
maryland
30000
22666.6667
7333.3333
college park
maryland
18000
22666.6667
-4666.6667
columbia
maryland
20000
22666.6667
-2666.6667
boston
massachussets
35000
22500.0000
12500.0000
molden
massachussets
10000
22500.0000
-12500.0000
jersey city
new jersey
35000
35000.0000
0.0000

How can i find the maximum gdp per population in sql?

I have 2 tables countries and coutry_stats.
Countries table
Country_id
name
country_code
1
Aruba
AW
2
Afghanistan
AF
Country_stats table
Country_id
year
population
gdp
1
1986
62644
405463417
1
1987
61833
487602457
1
1988
61079
596423607
1
1989
61032
695304363
1
1990
62149
764887117
1
1991
64622
872138730
2
1960
8996973
537777811
2
1961
9169410
548888895
2
1962
9351441
546666677
2
1963
9543205
751111191
2
1964
9744781
800000044
2
1965
9956320
1006666638
How can i find the maximum gdp / popupation along the years?
i tried
select
countries.country_id,
name,
country_code,
year,
gdp,
population,
max(gdp / population) as per_ratio
from
countries JOIN country_stats on
countries.country_id = country_stats.country_id
where
countries.country_id = 1 group by name order by per_ratio;
but im getting this
Country_id
name
country_code
year
gdp
population
per_ratio
1
Aruba
AB
1986
405463417
62644
27084.7037
the per_ratio is the correct maximum of this country but this is not the correct record in the database.
This would likely yield the result you're looking for - it sorts per_ratio DESC and limits that record to one.
SELECT
countries.country_id,
name,
country_code,
year,
gdp,
population,
gdp / population as per_ratio
FROM countries
JOIN country_stats
on countries.country_id = country_stats.country_id
WHERE countries.country_id = 1
ORDER BY per_ratio DESC
LIMIT 1;
Alternatively, you could use a partition to first get the max for the country id in a CTE, and then pull in all records where max_per_ratio = per_ratio
WITH MAX_PER AS(
SELECT
countries.country_id,
name,
country_code,
year,
gdp,
population,
gdp / population as per_ratio,
MAX(gdp/population) OVER(PARTITION BY country_id) AS max_per_ratio
FROM countries
JOIN country_stats
on countries.country_id = country_stats.country_id
WHERE countries.country_id = 1)
SELECT
country_id,
name,
country_code,
year,
gdp,
population,
per_ratio
FROM MAX_PER
WHERE max_per_ratio = per_ratio;

SQL groupby rollup vs union

Sql question:
enter image description here
competitor country
Acme Corp USA
GLOBEX USA
Openmedia France
K-bam USA
Hatdrill UK
Hexgreen Germany
D-ranron France
Faxla Spain
the output should be
country competitors
France 2
Germany 1
Spain 1
UK 1
USA 3
Total: 8
except using groupby with rollup, i am trying to solve it via "union" but turns out "order by is not functioning" (supposed to order by country name, but my output turns out to "order by competitors" ...)
This is my code:
(select country, count(competitor) as competitors
from table
group by 1
order by 1
)
union all
(select "Total:" as country, count(*) as competitors from table);
Any help would be appreciated! Thank you!
If you want the result ordered, you need an order by after the union:
(select country, count(competitor) as competitors
from table
group by 1
) union all
(select 'Total:' as country, count(*) as competitors
from table
)
order by (country = 'Total:') desc, country asc

Find MAX(Avg(value)) after grouped by two fields

The table name is c_list.
Country City Rating Date
------------------------------------
France Brest 95 24092016
France Brest 98 27092016
France Brest 95 03102016
France Lille 100 26092016
France Lille 92 28092016
Japan Tokyo 98 02102016
There are more than 50 different countries and each country have few cities. And each city may have more than one row of record or more. I want to select one City with highest average Rating (Compare to Cities in it's own country) and then compare with all other cities in different countries. So, the final query should display all Country and their ONE City with max(avg(Rating)) and in desc order. The sample output:
Country City max(avg(rating))
-------------------------------------
USA New York 97.25
UK Cardiff 96.70
Germany Greven 96.50
Turkey Afyon 94.88
France Guipavas 94.10
Canada Cartwright 91.35
I can only get the max(avg(rating)) for one country. Need help.
SELECT top 1 country, city, Avg(rating) AS Ratings
FROM c_list
where country = 'France'
GROUP BY city, country
order by Ratings desc
(Edited) The result that I want is similar like Miss world contest. Compete and win against local contestant in your country first. Next (my final result set) is to compete against the winners from other countries and rank them first to last using their avg(rating) that they got eatlier in their country.
If am not wrong you are looking for this
SELECT country,
city,
Avg(rating) AS Ratings
FROM c_list A
GROUP BY city,
country
HAVING Avg(rating) = (SELECT TOP 1 Avg(rating) AS Ratings
FROM c_list B
WHERE a.country = b.country
GROUP BY city
ORDER BY ratings DESC)
ORDER BY ratings DESC
Note : If you are using Mysql the replace TOP keyword with LIMIT
Base table:
select t.* from temp_lax t
COUNTRY CITY RATING
1 France Brest 95
2 France Brest 98
3 France Brest 95
4 France Lille 100
5 France Lille 92
6 Japan Tokyo 98
Query:
select t1.country, t1.city, Avg(t1.Rating) rating
from temp_lax t1
group by t1.country, t1.city
having avg(t1.rating) = (select max(avg(rating))
from temp_lax t2
WHERE t1.country = t2.country
GROUP BY t2.city)
order by rating desc
OUTPUT:
COUNTRY CITY RATING
1 Japan Tokyo 98
2 France Lille 96
3 France Brest 96
Please let me know if you are looking for different result set.

How can I write a query as a value in a row?

I have two tables on MySQL (using phpMyAdmin), looking like the following:
Table 1:
Country Total Minutes
USA 100
USA 90
Canada 60
Mexico 80
UK 90
France 70
France 10
Germany 10
In Table 2, what I need to do is the following:
Region Total Minutes
North America USA+USA+Canada+Mexico Mins
Europe UK+France+France+Germany Mins
Is there a way to have a row be the result of a query?
You either need a region column in table 1:
SELECT region, SUM(`Total Minutes`)
FROM timespent
GROUP BY region;
Or a separate region <-> country table:
SELECT region, SUM(`Total Minutes`)
FROM myregions r
INNER JOIN timespent t USING (country)
GROUP BY r.region;
The regions table would look like this:
region | country
--------------+--------
North America | USA
North America | Mexico
If you can't change anything in your database, look at Andomar's solution :)
You could translate the countries to regions in a subquery. The outer query can then group by on region:
select Region
, sum(TotalMinutes) as TotalMinutes
from (
select case country
when 'USA' then 'North America'
when 'France' then 'Europe'
end as Region
, TotalMinutes
from YourTable
) as SubQueryAlias
group by
Region