我有如下表格:
Car(id, make, ....)
Deal(id,datetime,car_id,....)
我想写一个会返回一年的查询,以及一辆汽车可以获得交易最多的汽车(即最多的交易ID)以及该汽车的交易数量。
我开始了,
SELECT YEAR(D.datetime) AS the_year, C.make, COUNT(D.id) AS num
FROM Deal D, Car C
WHERE D.car_id=C.id
GROUP BY the_year
不幸的是,这已经回归了当年和交易总数。
所以我想在另一个表中创建它,然后调用MAX(tbl.num)
,但我对语法感到困惑
有人可以帮帮我吗?
答案 0 :(得分:2)
这是一个有趣的问题。您正在寻找的是特别称为"模式"在统计中。在MySQL中,你可以通过使用变量或group_conat()
/ substring_index()`技巧来实现这一点。我将展示后者:
SELECT the_year,
substring_index(group_concat(cd.make order by num desc), ',', 1) as the_mark
FROM (SELECT YEAR(D.datetime) AS the_year, C.make, COUNT(D.id) AS num
FROM Deal D JOIN
Car C
ON D.car_id = C.id
GROUP BY the_year, c.make
) cd
GROUP BY the_year;
编辑:
使用变量的版本:
SELECT the_year,
substring_index(group_concat(cd.make order by num desc), ',', 1) as the_mark
FROM (SELECT YEAR(D.datetime) AS the_year, C.make, COUNT(D.id) AS num,
@rn := if(@year = YEAR(D.datetime), @rn + 1, 1) as rn,
@year := YEAR(D.datetime)
FROM Deal D JOIN
Car C
ON D.car_id = C.id CROSS JOIN
(SELECT @year := 0, @rn := 0) vars
GROUP BY the_year, c.make
ORDER BY the_year, num DESC
) cd
WHERE rn = 1;