获得前5名记录及其每月计数

时间:2017-02-15 16:27:43

标签: mysql sql

我正在使用phpmyadmin。 我有一个表格malicioussite。它包括2列调用region,其中包含ISO-3166-1 alpha-2代码,例如GB,US和adddate包含它的时间戳。

SELECT region, COUNT(*) AS total 
FROM malicioussite 
GROUP BY region
ORDER BY COUNT(*) DESC LIMIT 5

它给了我桌子的前5名记录,这是正确的:

region total
JP      7
US      6
RU      5
CN      4
DE      3

现在我想获得前5个记录及其过去6个月的每月记录。

SELECT region, MONTH(adddate) as Month, count(*) as Total
FROM malicioussite
where adddate BETWEEN DATE_FORMAT(NOW()-INTERVAL 5 MONTH, '%Y-%m-01 00:00:00') AND DATE_FORMAT(LAST_DAY(NOW()), '%Y-%m-%d 23:59:59')
GROUP BY YEAR(adddate), MONTH(adddate), region

它给了我所有的地区和过去6个月的每月计数。

region  Month  Total
  AQ      9      1
  AR     10      1
  KR     11      1
  GB     12      1
  HK     12      1
  JP     12      1
  US     12      1
  AS      1      1
  HK      1      1
  JP      1      2
  US      1      1
  CN      2      4
  DE      2      3
  JP      2      4
  RU      2      5
  US      2      4

这部分是正确的,但我想要的只是前5个地区,如下所示:

region  Month  Total
 JP     12      1
 JP      1      2
 JP      2      4
 US     12      1
 US      1      1
 US      2      4
 RU      2      5
 CN      2      4
 DE      2      3

有什么方法可以解决我的问题吗?

1 个答案:

答案 0 :(得分:0)

您已完成所有工作,只需添加子查询条件即可。

SELECT region, MONTH(adddate) as Month, count(*) as Total
FROM malicioussite
where adddate BETWEEN DATE_FORMAT(NOW()-INTERVAL 5 MONTH, '%Y-%m-01 00:00:00') 
AND DATE_FORMAT(LAST_DAY(NOW()), '%Y-%m-%d 23:59:59')  
AND region IN (SELECT region 
               FROM malicioussite 
               GROUP BY region
               ORDER BY COUNT(*) DESC LIMIT 5)
GROUP BY YEAR(adddate), MONTH(adddate), region

或使用加入

SELECT m.region, MONTH(adddate) as Month, count(*) as Total
FROM malicioussite m
JOIN (SELECT region 
      FROM malicioussite 
      GROUP BY region
      ORDER BY COUNT(*) DESC LIMIT 5) as top_reg
ON top_reg.region = m.region
where adddate BETWEEN DATE_FORMAT(NOW()-INTERVAL 5 MONTH, '%Y-%m-01 00:00:00') 
AND DATE_FORMAT(LAST_DAY(NOW()), '%Y-%m-%d 23:59:59')       
GROUP BY YEAR(adddate), MONTH(adddate), m.region