希望您能够帮助我使用这个MYSQL语句。我有一张这样的桌子:
|id |duration |start |
|1110460 |8.2 |20171211 |
|2221104 |8.9 |20171112 |
|1110460 |3.2 |20171113 |
|1110460 |4.4 |20171214 |
|3331938 |3.2 |20180115 |
|3331722 |5.4 |20171216 |
|1948212 |9.2 |20171217 |
|9219302 |3.2 |20171218 |
我想要做的是按给定开始月份的降序排列前4个ID。
例如,对于201712的前4个ID:
|id |duration |
|1110460 |12.6 |
|1948212 |9.2 |
|3331722 |5.4 |
|9219302 |3.2 |
任何帮助将不胜感激。这是我到目前为止所做的,但它一直在返回错误的结果:
SELECT id, sum(duration) FROM table WHERE
start LIKE '201712%' ORDER BY sum(duration) DESC LIMIT 4
答案 0 :(得分:0)
您应该使用分组
SELECT id, sum(duration)
FROM table
WHERE start LIKE '201712%'
GROUP BY id
ORDER BY sum(duration) DESC LIMIT 4
答案 1 :(得分:0)
要获得4个不同的最大总和及其ID,您可以使用以下
SELECT a.id, a.sum_duration
FROM (SELECT id, sum(duration) sum_duration
FROM demo
WHERE `start` LIKE '201712%'
GROUP BY id
) a
JOIN (SELECT distinct sum(duration) max_durations
FROM demo
WHERE `start` LIKE '201712%'
GROUP BY id
ORDER BY sum(duration) DESC
LIMIT 4
) b on a.sum_duration = b.max_durations
如果2个ID具有相同的总和
,则上述版本将返回超过4行