Query including the sum of one row in all rows - mysql

I'm trying to add in a column the sum of one of my columns and then show it for all of my rows. Specifically, I have a table where each row is a country, and there is a column identifying them with a region. A Third column is a measure. What I'm trying to do is sum the measures that are from the same region, and then show them for evert country.
This is my query so far:
SELECT country, region, SUM(share) AS value_sum FROM data_xlsx_Hoja2 GROUP BY region
I know that the group by makes it to appear just by region, but are those values resulting from the sum the ones that I want to place next to each country. Right now what I get is a table including the first country from every region and then the sum.
Any ideas?

I suppose your country information is more specific than region information.
So you can wirte a main query to return two informations, country and region, and a subquery to return the sum about all countries in the same region.
Try this:
SELECT main.country, main.region,
(SELECT SUM(sec.share)
FROM data_xlsx_Hoja2 sec WHERE sec.region = main.region) as total
FROM data_xlsx_Hoja2 main

You appears to want correlation subquery :
SELECT country, region,
(SELECT SUM(d1.share)
FROM data_xlsx_Hoja2 d1
WHERE d1.region = d.region
) AS value_sum
FROM data_xlsx_Hoja2 d;

Related

SUM before JOIN in MySQL?

I'm having a probably basic problem with an SQL query (I'm learning).
I'm tracking the vaccination status in the different Spanish regions.
Simplifying, I have two tables: one with the regions (ca) and their population, and the other with the region (ca), the day of each data (time) and the dosis administered.
In order to get the percentages of overall Spanish population vaccinated each day, I need to SUM all the populations of each region, and then divide the SUM of doses administered in all regions and then divide between that SUM.
However, when I do the JOIN, each population is added to every row, so the SUM is very high (it is counted once per time the region appears).
I think I need to SUM all the population before JOIN, but then, what column do I use to JOIN?
It is something like this:
SELECT
time AS "time",
SUM(SUM(v1.dose)) OVER (ORDER BY time)/'SP_population'
FROM vaccines v1
INNER JOIN
(SELECT SUM(population) AS 'SP_population' FROM ca_population) v2 ON ?????
GROUP BY time
ORDER BY time```
What should the ??? be?
If I understand correctly, you want a CROSS JOIN. You no longer care about regions so you want one population value for all rows:
SELECT v.time, p.sp_population, v.daily_dose,
SUM(SUM(v.daily_dose)) OVER (ORDER BY time) / p.sp_population
FROM (SELECT v.time, SUM(v.dose) as daily_dose
FROM vaccines v
GROUP BY v.time
) v CROSS JOIN
(SELECT SUM(population) as sp_population
FROM ca_population
) p
ORDER BY time

SQL: What country has the most cities?

Hello I started using MySQL and I seem to be having trouble trying to nest formulas. I'm working on a problem and the question is, What country has the most cities?
I have two tables:
CITY:
city
city_id
country_id
COUNTRY:
country
country_id
I am able to join the two tables together to get the cities to match with the countries but after that I don't know how to count to the country that has the most cities.
My current code is:
SELECT city.city, country.country
FROM city, country
WHERE city.country_id = country.country_id
From there I don't know how to add a count function without it coming back as as error. I dont fully understand the basics of nesting.
Thank you, any help is appreciated.
You do not need to do nesting necessarily. To simply know, which country has most number of cities, just use group by:
select country_id, count(1)
from city
group by country_id
This will give you the number of cities in each country. Then you could use a CTE to get the country with the largest number of cities.
You need to GROUP BY if you want to use aggregate functions.
Given the fact that you're very new to this I think you'll get a lot more out of this if you spend a few minutes reading up on some documentation. Don't worry, this is easy stuff so you'll understand this in no time. Please have a look at the following basic info (MySQL GROUP BY basic info) regarding the use of GROUP BY in MySQL. Your questions are answered in the topic regarding 'MySQL GROUP BY with aggregate functions'.
Basic group by:
SELECT
status, COUNT(*)
FROM
orders
GROUP BY status;
Group by using a join:
SELECT
status, SUM(quantityOrdered * priceEach) AS amount
FROM
orders
INNER JOIN
orderdetails USING (orderNumber)
GROUP BY status;
SELECT x.country
FROM country x
JOIN city y
ON y.country_id = x.country_id
GROUP
BY x.country
ORDER
BY COUNT(*) DESC LIMIT 1;
On the (fantastically unlikely) chance that the most civilised countries have equal numbers of cities, you would have to amend this a little.
What makes this difficult is possible ties, i.e. two or more countries sharing the maximum number of cities. As of MySQL 8 you can use window functions to help you with this. Here I compare the country counts and their maximum and then pick the rows were the two match.
select *
from country
where (country_id, true) in -- true means it is a maximum city country
(
select country_id, count(*) = max(count(*)) over()
from city
group by country_id
);
Sorry it was my first post, my code looks terrible.
following my code again.
select
country.country_id,
count(city.city_id)
from
country
inner join
city
on
city.country_id=country.country_id
group by
city.country_id
having
count(city.city_id) =
(SELECT
max(count(city.city_id))
FROM
city
GROUP BY
city.city_id);
Best regards,
Jens
Try the following code:
**select
country.country_id,
count(city.city_id)
from
country
inner join
city
on
city.country_id=country.country_id
group by
city.country_id
having
count(city.city_id) =
(SELECT
max(count(city.city_id))
FROM
city
GROUP BY
city.city_id);**
You need to group by country_id to make sure all cities that are connected to one country_id can be counted.
Where is a good approach, however it does not work together with "group by" as it will be accounted before the "group by" command.
The way you joined your data from different tables is not a very proper yet working way. I suggest to use the inner join in this case to make the command more obvious/better readable.
Count() is used to count the number of cities that accumulate on one country
max() is used to get the country with the most cities (highest count()).
SELECT country_id, count(1)
FROM city
GROUP BY country_id
ORDER BY count(1) desc;
Try following Code -
SELECT *,
(SELECT COUNT(*) FROM cities WHERE cities.country_id=C.country_id) as cities_count
FROM country C
ORDER BY cities_count DESC
LIMIT 0,1
Also is joining the two tables necessary? In your query, you said you need to find What country has the most cities?
Above query will only return one country with max cities.
You can find the country like this:
SELECT MAX(c.id) FROM (SELECT COUNT(id) AS id
FROM city group by country_id) c

Select from Two tables last name first name and avg salary in descending order by last name

Actor table
Castings table
I am new to SQL and am stuck on a problem I am working on. I am wanting to display the last name, first name and avg salary of an actor. The salary and the actor's name is in two different tables. , Also I would like to display the results in descending order according to the actors last name. Here is what I have written up but I cannot get it to compile correctly. I have provided a screenshot of what I have so far.
You use JOIN but didn't use on to connect two table, from your tables you might use actorID columns to be the connected condition.
when you use an aggregate function you might use non-aggregate columns in group by
SELECT a.lname,a.fname,AVG(c.salary)
FROM Actor a
JOIN Castings c on a.actorID = c.actorID
group by a.lname,a.fname
order by a.lname desc
Here is a link talking about JOIN

Use subquery and possible join to get population percentage

I'm learning MySQL and I want to make two queries divide the sum(populationcount) values in each query to arrive at a percentage (as a decimal value) listed in a separate column. The goal is to use the first query that I will list below as a subquery to show the percentage of each type of education attained by each of the age groups.
The query that I need to use as the subquery is this:
SELECT age,SUM(populationcount) FROM educational_attainment GROUP BY age;
Population count results in only three different values, which are to be the divisor values in the new query.
The other query that I need to use values from is this:
SELECT sum(populationcount), age, educationalattainment from educational_attainment group by age, educationalattainment
The results here show 12 different values for populationcount, one for each level of education attained within each age group.
The query I have that is coming somewhat close looks something like this:
SELECT A.EducationalAttainment, A.age, A.populationcount/B.age FROM educational_attainment A JOIN (SELECT age, sum(populationcount) age_populationcount FROM educational_attainment GROUP BY age) B ON A.age=B.age;
Unfortunately, it's giving me way too many results for each age group and the calculated values are greater than 0 instead of a decimal value less than 0.
I hope I explained this well enough. If anyone has any insight on what I'm doing wrong, I would greatly appreciate your input! Thanks!
You should use a LEFT JOIN instead as illustrated below:
SELECT
A.age, B.educationalattainment,
(IFNULL(B.pop_count, 0)/A.pop_count)*100 percentage_pop
FROM
(SELECT
age, SUM(populationcount) pop_count
FROM educational_attainment
GROUP BY age) A
LEFT JOIN
(SELECT
sum(populationcount) pop_count, age, educationalattainment
FROM educational_attainment
GROUP BY age, educationalattainment) B
ON A.age=B.age;

mysql group by multiple

I'm not sure if this is specifically a group by question, as I've tried grouping this by multiple columns. Basic problem is a table like this:
I would like to get the sum of the order total_price for different countries, but grouped by the order_id. So for France the sum of total_price should be 8000 as two of the rows are for the same order. My sql is clearly wrong as I am not getting this.
SELECT sum(total_price) as total_price_per_country
FROM cars
WHERE (country IN ('France'))
group by order_id, country;
Nope, GROUP BY won't quite get you that. If you GROUP BY country you get one row per country.
There's no way to do this without a second query, so it'd have to be something like this:
SELECT *, (SELECT SUM(total_price) FROM cars AS c2 WHERE c2.country = cars.country) AS total_price_per_country
FROM cars
(An INNER JOIN to a second copy of the table would work too.)
select sum(total_price) from cars where country = 'France' group by order_id
Try above query