I have a database with the tables: VEHICLES (a Blue Honda Civic costing $30k), BRAND (Honda) AND MODEL (Civic).
I am trying to create a correlated sub query which will give me the VEH_IDs for the cars with the highest price from each BRAND.
Simply, I want to know for all the brands which car costs the most.
I've attached a picture with the SQL im trying but it's not working. Most likely because I have no idea what im doing.
SELECT
BRAND.BRAND_ID, BRAND_NAME, VEHICLE.MODEL_ID, VEH_ID
FROM BRAND, MODEL, VEHICLE
WHERE VEH_PRICE =
(
SELECT MAX(VEH_PRICE)
FROM VEHICLE
)
GROUP BY BRAND.BRAND_ID, BRAND_NAME, VEHICLE.MODEL_ID, VEH_ID;
create a new query on the vehicles table grouping by brandID to determine the max(price)
SELECT brandID, MAX(VEH_PRICE)
FROM VEHICLE
group by brandID
then create another query that uses the first one joined back to vehicles to determine the related vehicleID
SELECT
v.BRAND_ID, MODEL_ID, VEH_ID
FROM VEHICLE v inner join
( SELECT brandID, MAX(VEH_PRICE) as max_veh_price
FROM VEHICLE
group by brandID) m on
v.brandid = m.brandid and
v.veh_price = m.max_veh_price
then, to get the brand_name, join again to your brand table on the brandID field, and yes, if max(price) returns more than one vehicle, you'll have to go with Top 1 at Roman suggests.
sorry, couldn't read your images at first.
yes, you need to join the model table to vehicle to get to the brandID. I'm assuming this is an exercise and you're supposed to learn about joins as a result? don't just take a solution, then, understand each piece individually.
Related
I have a basic question regarding a problem I faced:
Let's say I have this model with these tables :
Food(Quantity, Animal_id)
Race(Race_code, Race_name)
Animal(Animal_id, Race_code)
I have been asked to find the total quantity eaten by each race with select query.
(Of course by using SUM function. Race_name is also required for the display)
But I don't know to link the attributes of these tables to go from the quantity to the race name (I only know that my reasoning will be like this Quanity->animal_id->race_code->race_name). Any help ?
Looks like a join, doesn't it? Columns that aren't aggregated (race_name in this case) have to be put into the group by clause.
select r.race_name,
sum(f.quantity) sum_quantity
from race r join animal a on a.race_code = r.race_code
join food f on f.animal_id = a.animal_id
group by r.race_name;
Using subquery:
select race_name ,(select sum(quantity) from food where animal_id in (select animal_id from animal a where r.race_code = a.race_code))
from race r
Context: I want to know which vehicle brand appears the most in different accidents.
I have the table vehicle (v_number, brand).
Problem is, I have two different accident tables:
One refers to driven cars involved in an accident, let's call it acc_drive (v_number, acc_number, driver) [v_number FK vehicle]
The other refers to parked cars which are involved in an accident, let's call it acc_park (v_number, acc_number) [v_number FK vehicle, acc_number FK acc_drive]
Now, I'm trying to get the vehicle brand which appears the most in the total of the two tables. For example, if Audi cars appeared 2 times in acc_drive and 3 times in acc_park, the total number of appearences would be 5.
I'm having a really hard time trying to figure this out, so a helping hand would be much appreciated!
UNION ALL can be used to bring the tables together for the JOIN:
select v.brand, count(a.v_number)
from vehicle v left join
((select v_number
from acc_drive
) union all
(select v_number
from acc_park
)
) a
on v.v_number = a.v_number
group by v.brand
order by count(v_number) desc; -- put the biggest numbers first
Note that this uses a left join. So brands with no accidents will be included in the results.
Try this-
SELECT TOP 1 brand,COUNT(*)
FROM vehicle A
INNER JOIN acc_drive B ON A.v_number = B.v_number
INNER JOIN acc_park C ON A.v_number = C.v_number
GROUP BY brand
ORDER BY COUNT(*) DESC
Basically I am doing a movie rental company database.
I need to be able to Give the names of movies that made more money than any other movie within their category.
Currently, I have a product table and rental table.
Product –
Attributes: (Product_ID, Product_Title, Rating, Release_Date, Genre, Length_of_Movie, Director_Name, Key_Actor, Num_Copies)
PK – Product_ID
Rental –
Attributes: (Rental_ID, Member_ID, Product_ID, Date_Rented, Date_Returned)
PK – Rental_ID
FK – Member_ID, Product ID
Each rental has a value of $1.00. I was able able to get the revenue of all the rentals, but I am struggling to get it by genre or category. I got the revenue as a whole by this query:
Select sum(count(Rental_ID) *1) as Revenue
from Rental
Group by Rental_ID;
** every rental is $1.00 so it was a simple calculation to just count how many times a unique rental number was created and multiply it by the flat fee.
I now need to break that down, and give the highest earner per genre or category. I'm completely stumped... any help would be appreciated. Thanks.
I haven't test this but:
I'd create a view to get revenue per product like so
Create View RevenuePerProduct As
Select
r.Product_ID,
Count(*) As Revenue -- as $1/rental we can just count
From
Rental r
Group By
r.Product_ID
To get the maximum earnings by Genre you can utilise the view, and I'll make another view called MaxRevenueByGenre.
Create View MaxRevenueByGenre As
Select
p.Genre,
Max(rpp.Revenue) As MaxByGenre
From
RevenuePerProduct rpp
Inner Join
Product p
On rpp.Product_ID = p.Product_ID
Group By
p.Genre
To get the product (or products) that had the maximum revenue per genre is a bit more tricky as you need to refer to the revenue part twice. You'll notice both views are used.
Select
best.Genre,
best.ProductTitle,
rpp.Revenue
From
Product best
Inner Join
RevenuePerProduct rpp
On best.Product_ID = rpp.Product_ID
Inner Join
MaxRevenueByGenre mpg
On best.Genre = mpg.Genre And rpp.Revenue = mpg.MaxByGenre
This will produce more than one result for each Genre if they are tied for highest earner.
You can get by without views, by substituting the select statements of the view inside parenthesis if you prefer.
I have one table containing car inventory. This has two columns one is car_id and the other is car_info e.g. bmw 320
The other table also contains a table with two columns. One is sales_ids and the other is car_id they have sold.
I want to create an sql query were the output will be the sales_id and the car name which was sold by that sales_id.
I have tried using a join query but have had no sucess thus far. Can anyone offer some help
select s.sales_id, i.car_info
from inventory i
join sales s on s.car_id = i.car_id;
To find cars sold for one specific sales_id:
select i.car_info
from inventory i
join sales s on s.car_id = i.car_id
where s.sales_id = 'some id';
select c.car_id,c.car_info,s.sales_id from
car_table_name c,
sales_table_name s
where c.car_id = s.car_id
Assuming table one is named car_inventory and table two car_sales the query should be this.
However for a better answer you should provide the code you try with your question.
select car_sales.sales_ids, car_inventory.car_info
from car_sales join car_inventory
on car_sales.car_id = car_inventory.car_id
really hope someone can help me on this one!
I have 6 tables:
Products
prodid
Prodequipment
prodid
equipclassmain
equipclassor
Equipclasses
classid
Equipfunctions
equipid
classid
Equipment
equipid
Workshopequipment
workshopid
equipid
Products – a list of some products
Equipment – a list of some equipment
Prodequipment – lists what equipment is needed to do a product. You can use equipment listed in equipclassmain or replace it by equipment in equipclassor. Table Products has one to many relation to table Prodequipment, i.e. you will use many different tools (equipment) to produce one product, but you can choose to use anyone in the pair equipclassmain/equipclassor. For instance to frame a photo you can use a wooden frame or plastic frame (one pair) and a cover glass or cover plastic (second pair). You can combine it as you wish, but both pairs should be used: wooden frame with cover glass or plastic frame with cover glass or wooden frame with plastic cover or plastic frame with plastic cover.
Equipfunctions and Equipclasses – Because one piece of equipment can be used in different ways it is not linked directly to table Prodequipment. I have created table Equipclasses where all single use of every possible equipment is listed and table Equipfunctions where I list those single uses for every equipment.
Workshopequipment – lists workshops and equipment they are using.
Now I need a list of products which can be manufactured by two different given workshops (let's say workshopid = 1 and workshopid = 4), i.e. both those workshops have all equipment needed to produce those products. Bear in mind that those workhops don't have to use the same equipment to do so as I described above.
I'm trying with this query:
SELECT prodid FROM Products JOIN (
SELECT workshopid, prodlist, equipclassmain, equipclassor,
if( LOCATE( equipclassmain, prodlist ) >0
AND LOCATE( equipclassor, prodlist ) >0, 1, 0 ) AS pairstatus FROM Prodequipment JOIN
(
SELECT classid FROM Equipclasses JOIN (
SELECT classid FROM Equipfunctions JOIN (
SELECT workshopid, GROUP_CONCAT( equipid ) AS prodlist FROM Workshopequipment
GROUP BY workshopid
)
equipfunclist GROUP BY equipid
) equipclasslist GROUP BY classid
) WorkshopequipmentList HAVING pairstatus = 1 AND workshopid in (1, 4)
) prodbyworkshops ON classid = equipclassmain OR classid = equipclassor
But I get an "Column classid in field list is ambiguous". Any idea what's wrong here?
THANK YOU!
Your query references multiple tables that have a classid column.
Therefore, when you reference classid in the HAVING clause, it doesn't know which table to get the classid for.
You need to write tablename.classid where tablename is the name of the table containing the classid column. (Probably equipclasslist; I didn't look at the query)
It's from the part of the query with:
...
SELECT classid
FROM Equipclasses JOIN (
SELECT classid
FROM Equipfunctions...
Both EquipClasses and the inner query have a classId. You need to specify which you're selecting.