嘿所以我有一个问题。 我有两张桌子。 table1和table2。 表1:
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
表2:
id | price | type_id
1 100 1
2 200 1
3 300 2
4 400 2
5 500 3
我想要的是显示&#39;类型&#39;&#39; car_numbers&#39;以及每种车型的平均价格。基本上我在这两个表之间想要的结果是:
type | car_numbers | average_price
bmw 8 150
mercedes 6 350
chevrolet 1 500
我该怎么做?我知道我必须与两个表中常见的type_id相关但我该怎么做?
答案 0 :(得分: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
答案 1 :(得分:1)
我想你可能正在寻找
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
答案 2 :(得分:0)
这就是你要找的,使用Group By和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