Reputation: 574
Hey so I have a question. I have two tables. table1 and table2. table1:
id | car_numbers | type | model | type_id
1 3 bmw <model1> 1
2 5 bmw <model2> 1
3 2 mercedes <model1> 2
4 4 mercedes <model2> 2
5 1 chevrolet <model1> 3
table2:
id | price | type_id
1 100 1
2 200 1
3 300 2
4 400 2
5 500 3
What I want, is to display the 'type', the 'car_numbers' and the average price of each car type. Basically the result of what I want between those two tables is:
type | car_numbers | average_price
bmw 8 150
mercedes 6 350
chevrolet 1 500
How can I do that? I know I have to relate to the type_id that's common in both tables but how can I do that?
Upvotes: 0
Views: 70
Reputation: 149
I think it might be this you are looking for
SELECT t.name, sum(Distinct o.car_number) car , avg(w.price) price FROM
TYPE t
INNER JOIN tone AS o ON o.type_id = t.id
INNER JOIN ttwo AS w ON w.type_id = t.id
GROUP BY t.name
http://sqlfiddle.com/#!2/1937a/51
Upvotes: 1
Reputation: 780994
SELECT type, car_numbers, AVG(price) AS average_price
FROM (SELECT type_id, type, SUM(car_numbers) AS car_numbers
FROM table1
GROUP BY type_id) AS t1
JOIN table2 AS t2 ON t1.type_id = t2.type_id
GROUP BY type
Upvotes: 1
Reputation: 1083
Is this what you are looking for, usage of Group By and Avg:
SELECT type, car_numbers, avg(price) AS average_price
FROM table1 T1
INNER JOIN table2 T2
ON T1.type_id = T2.type_id
GROUP BY type, car_numbers
Upvotes: 0