每年如何查询?

时间:2018-12-07 08:08:52

标签: mysql sql

我想问一个问题:每年哪个生产商销售的汽车最多?我可以在查询中定义年份,但是每年如何自动列出?

SELECT producer, COUNT(type) AS counter
FROM `car` 
INNER JOIN producer ON car.producer= producer.id 
WHERE produce_year = 2000 
GROUP BY type 
ORDER BY COUNT(type) DESC 
LIMIT 1

2 个答案:

答案 0 :(得分:0)

将年份添加到GROUP BY中。删除WHERE子句。

SELECT producer, produce_year, COUNT(type) AS counter
FROM `car` 
INNER JOIN producer ON car.producer = producer.id 
GROUP BY producer, produce_year 
ORDER BY COUNT(type) DESC 

答案 1 :(得分:0)

这将起作用:

select * from (SELECT producer, COUNT(type) as cou
,RANK() OVER (PARTITION BY produce_year ORDER BY COUNT(type)) AS myrank
FROM car c 
INNER JOIN producer p ON c.producer= p.id  
GROUP BY  produce_year) 
where myrank=1;