0

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?

2
  • 2
    This is a basic join query with a group by. You should know these basic constructs in MySQL if you are using the database. Commented May 16, 2014 at 22:03
  • How exactly do you define average price? Commented May 16, 2014 at 22:27

3 Answers 3

1
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

DEMO

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

1 Comment

GROUP BY type, car_numbers ??? Why would you want to group by car_numbers???

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.