MySQL - 使用LIMIT和GROUP BY

时间:2014-06-23 12:14:54

标签: mysql

我看过很多类似头衔的问题,但在我的特定情况下没有一个真正有用:

QUERY

SELECT YEAR(start_time) AS year, MONTH(start_time) AS month, COUNT(*) AS calls, to_number
FROM calls
WHERE organisation_id = 123 AND direction = 'inbound'
GROUP BY YEAR(start_time), MONTH(start_time), to_number
ORDER BY YEAR(start_time), MONTH(start_time), DAY(start_time) ASC

这几乎给了我想要的每月每个号码的呼叫次数,但我想限制每个月的结果数量。目前,它将返回每月每个数字的计数,可以是零到几百个。

e.g。在当前查询中,本月的结果可能是:

year | month | calls | to_number   |
------------------------------------
2014 |   6   |  1856 | 44123456789 |
2014 |   6   |  1800 | 44123456788 |
2014 |   6   |  1456 | 44123456790 |
2014 |   6   |  1256 | 44123456791 |
2014 |   6   |  1151 | 44123456792 |
2014 |   6   |  1056 | 44123456793 |

所以,当我想LIMIT到5时(那些通话次数最多的那些),当月有6个结果。

修改

SQLFiddle http://sqlfiddle.com/#!2/f915bd/1

更新

我试图复制这个答案https://stackoverflow.com/a/15585351/634120,但由于我使用了几个月年,这似乎是解决问题的不合适方法。

SELECT   to_number, GROUP_CONCAT(year(start_time), month(start_time) ORDER BY id DESC)      grouped_year
FROM     calls
WHERE direction = 'inbound' AND organisation_id = 123
GROUP BY to_number

此结果不能用于查询的下一阶段,因为结果包含月份和年份,例如原始问题中的20146代替2014,这意味着时间戳的年份和月份为2014-06。由于答案的下一部分依赖于解析此GROUP_CONCAT结果,因此它不适用于我的方案。

然后我尝试将this answer合并到我的查询中,但我运行的错误是unknown column start_time in field list

SELECT YEAR(start_time), MONTH(start_time), to_number, COUNT(*)
FROM (SELECT YEAR(start_time), MONTH(start_time), to_number, COUNT(*), IF(@lasttype = (@lasttype:=a.type), @index:=@index+1, @index:=0) indx 
      FROM (SELECT YEAR(start_time), MONTH(start_time), to_number,  COUNT(*) 
            FROM calls
            WHERE organisation_id = 123 AND direction = 'inbound'
            GROUP BY to_number, YEAR(start_time), MONTH(start_time)
            ORDER BY YEAR(start_time), MONTH(start_time) ASC
            ) h, (SELECT @lasttype:='', @index:=0) AS a
    ) h 
WHERE h.indx <= 5;

我不相信这是Using LIMIT within GROUP BY to get N results per group?的副本,因为这个问题只涉及多年,而我考虑了几个月和几年,因此那里依赖于这个事实的答案是& #39; t适合这个问题。

0 个答案:

没有答案