mysql group by multiple - mysql

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

Related

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 which should give the number of unique n in an 1:n realtionship

Hello i've got a short question.
For an exercise at the university i've got a full joined table.
In this table is a column called supplier and a column prduct_id.
Now i want to make a select which does the following:
I want to get the number of unique (DISTINCT) product_id's for each supplier
i've tried the following, but it give me the number of all row's grouped by the supplier
SELECT DISTINCT COUNT(`product_code`),`id_supplier` FROM `refactored_data`
GROUP BY `refactored_data`.`id_supplier` ORDER BY
`refactored_data`.`id_supplier` ASC
Try this:
SELECT COUNT(DISTINCT product_id), id_supplier
FROM refactored_data
GROUP BY id_supplier
So it seems your query is actually simpler than you think.
You are grouping by supplier and count products. Then you say you only want distinct results, which doesn't change anything, because your results are already unique.
Move the DISTINCT inside your COUNT, so as to count distinct values, rather then making your lines distinct.
SELECT COUNT(DISTINCT product_code), id_supplier
FROM refactored_data
GROUP BY id_supplier
ORDER BY id_supplier ASC;

Count numbers of records for member id

I am working on a little project for one of my customer. Basically I want to count the number of invoice per member ID. Each row of my tblinvoice has a column called member_id.
I have a gridview setup and stuff but I really have no clue how to count them.
like :
SELECT * FROM tblinvoices WHERE member_id=#membered
what would be the correct MySQL CMD?
Cheers,
Pierre
Try this
SELECT count(*) as total FROM tblinvoices WHERE member_id=#membered
SELECT count(member_id) as total FROM tblinvoices WHERE member_id=#membered
#Krish R comment should work.
But if what you want is to get a list of all members (you said sth about a gridview...), and for each of them, get the number of invoices:
SELECT member_id, count(*) as totalno
FROM tblinvoices
GROUP BY member_id
You can use Count in your sql query to get the ouptut....
SELECT count(*) as tt FROM tblinvoices WHERE member_id=#membered

MySQL - selecting the count of an id where one count is greater than another count

Pretty new to sql statements here so this one is a bit tricky for me.
I have two tables: sold and product. Sold(SID, UPC, Date) Product(UPC, Name, Brand)
I need to find in how many stores(sid) does one brand outsell another brand.
I was thinking it was something like:
select count(*) from sold natural join product
where count(brand = 'sony') > count(brand = 'samsung');
Clearly that isn't valid however...
SELECT COUNT(*)
FROM (
SELECT SID
FROM Sold
JOIN product
ON product.UPC = Sold.UPC -- otherwise we have a cartesian product
GROUP BY SID -- if we need totals _by store_, we need to group on that.
HAVING SUM(brand='sony') > SUM(brand='samsung')
) Totals.

MySQL Group two column with where clause on both two group

What I have:
I have two table , first is user_faktorha save invoices data and second is u_payment save payment data .
What I want:
I want to group all data from this two table and have a result as one table with sum both table.
My two table with sample query's is on sqlfiddle : http://sqlfiddle.com/#!2/b9f9e/4
What's problem:
I try to solve this problem , but give wrong result each time , for example (can be see on sqlfiddle) , user/tell named as habib on give wrong sum(price) result.
habib's faktorhaprice = -508261 and habib's paymentprice = 648000 but sum result in main query have wrong data -7115654 and 13000000
what's the solution ?
(Updated) One way:
SELECT tell,SUM(FAKTORHAPRICE) FAKTORHAPRICE, SUM(PaymentPrice) PaymentPrice
FROM (SELECT tell, price as FAKTORHAPRICE, null PaymentPrice
from user_faktorha
union all
SELECT Username as tell, null as FAKTORHAPRICE, Price as PaymentPrice
FROM `u_payment` WHERE Active='1') sq
GROUP BY tell ORDER BY FAKTORHAPRICE ASC;
SQLFiddle here.
The essence of your problem here is that you are trying to relate to unrelated tables. Sure they have common data in the user name, but there is not a clean relation between them like an invoice id that can be used to relate the items together such that the OUTER JOIN wouldn't duplicate records in your result set. My suggestion would be to do the aggregation on each table individually and then join the results like this:
SELECT f.tell, f.faktorhaprice, p.paymentprice
FROM
(SELECT tell, SUM(price) AS faktorhaprice FROM user_faktorha GROUP BY tell) AS f
INNER JOIN
(SELECT username, SUM(price) AS paymentprice FROM u_payment GROUP BY username) AS p
ON f.tell = p.username