我有两个SQL表:cars和lap_times。
cars:
- car_id
- engine_size
- car_type
lap_times
- lap_time_id
- time
- car_id
我希望得到以下内容: - 每辆车的车型数量 - 每辆车的平均发动机尺寸 - 每辆车中所有车型的最快圈数
我有这个:
SELECT
COUNT(cars.car_id),
AVG(cars.engine_size),
lps.FASTEST_LAP
FROM
cars,
(SELECT lap_times.car_id AS C_ID, MIN(lap_times.time) AS FASTEST_LAP FROM lap_times) as lps
WHERE
cars.car_id = lps.C_ID
GROUP BY
cars.car_type
但我没有得到任何东西。不过,我没有收到任何错误。有什么想法有什么不对吗?
答案 0 :(得分:0)
问题在于您的子查询,您希望子查询返回最快的car_id并返回一些car_id。
我建议您了解GROUP BY and HAVING with Hidden Columns
此外,如果您的子查询按预期运行,则只会选择一辆车而不是car_type的一辆车。
这是作业吗?你应该标记它。
答案 1 :(得分:0)
试试这个:
SELECT a.Car_Type,
COUNT(a.car_ID) as NoOfCars,
AVG(a.engine_size) as AverageEngine,
MIN(b.time) as Fastest
FROM cars a INNER JOIN lap_times b ON
a.Car_ID = b.Car_ID
GROUP BY a.car_id
答案 2 :(得分:0)
尝试以下方法:
SELECT cars.car_type,
COUNT(cars.car_id),
AVG(cars.engine_size),
MIN(lps.FASTEST_LAP)
FROM cars,
lap_times
WHERE cars.car_id = lps.C_ID
GROUP BY cars.car_type
答案 3 :(得分:0)
with CTE as(
select car_type, count(*) as count_cars, avg(engine_size) as avg_engine
from cars C
group by car_type
)
select * ,
(SELECT MIN(time) FROM lap_times where car_id in (select car_id from cars where car_type=CTE.car_type))
from CTE
答案 4 :(得分:-1)
没关系。通过在子查询内部进行分组来修复它。
SELECT
COUNT(cars.car_id),
AVG(cars.engine_size),
lps.FASTEST_LAP
FROM
cars,
(SELECT lap_times.car_id AS C_ID, MIN(lap_times.time) AS FASTEST_LAP FROM lap_times GROUP BY lap_times.car_id) as lps
WHERE
cars.car_id = lps.C_ID
GROUP BY
cars.car_type