MYSQL查询计数+当前月份不同

时间:2015-06-20 13:00:08

标签: php mysql

此mysql表具有所有用户的交易历史记录,例如

rec_id   |  rec_timestamp         | user_name
1        |  2015-06-06 12:30:00   | userA
2        |  2015-06-07 14:32:30   | userA
3        |  2015-06-08 15:35:12   | userB
4        |  2015-06-09 16:30:22   | userB
5        |  2015-06-10 16:30:22   | userC
6        |  2015-06-11 16:30:22   | userA
7        |  2015-06-12 16:30:22   | userB
8        |  2015-06-13 16:30:22   | userD
9        |  2015-06-14 16:30:22   | userE
10       |  2015-06-14 18:30:22   | userA
11       |  2015-06-15 16:30:22   | userF
12       |  2015-06-16 16:30:22   | userB
  1. 我想查询mysql,让5个用户名在当前月份中记录最多 - 按降序分类,比如谁有更多记录,将是第一个
  2. 我想在5个用户名中的每一个旁边显示,有多少条记录?
  3. 示例:

    Top 5 this month are: 
    TOP#1 is UserA with 33 records
    TOP#2 is UserD with 22 records
    TOP#3 is UserE with 10 records
    TOP#4 is UserB with 8 records
    TOP#5 is UserF with 4 records
    

    我试过了:

    SELECT DISTINCT(user_name), COUNT(rec_id) 
    FROM transactions 
    WHERE MONTH(CURDATE()) = MONTH(rec_timestamp) 
    SORT BY rec_timestamp DESCENDING LIMIT 5
    

    但它没有用。我做错了什么?

2 个答案:

答案 0 :(得分:0)

您可能需要在where子句和月份中包含年份。然后你需要一个GROUP BY和正确的逻辑:

SELECT username, COUNT(recid)
FROM transactions
WHERE YEAR(CURDATE()) = YEAR(update_timestamp) AND
      MONTH(CURDATE()) = MONTH(update_timestamp)
GROUP BY username
ORDER BY COUNT(recid) DESC
LIMIT 5;

实际上,最好以“sargable”方式进行日期算术 - 这意味着可以使用update_timestamp上的索引。查询看起来更像是这样:

SELECT username, COUNT(recid)
FROM transactions
WHERE update_timestamp >= date_sub(CURDATE(),  interval day(CURDATE()) - 1 day) AND
      update_timestamp < date_add(date_sub(CURDATE(),  interval day(CURDATE()) - 1 day), interval 1 month)
GROUP BY username
ORDER BY COUNT(recid) DESC
LIMIT 5;

答案 1 :(得分:0)

这样的事情会起作用。

SELECT MIN(user_name), COUNT(rec_id)
FROM tran_history
WHERE rec_timestamp >= '2015-06-01' AND rec_timestamp < '2015-07-01' 
GROUP BY user_name
ORDER BY COUNT(rec_id) DESC 
LIMIT 5

MIN(user_name)对于MySQL不是必不可少的,但对于SQL变种(例如不喜欢在GROUP BY语句中混合非聚合字段的SQL Server)的良好实践。