如何在一年的同月期间进行查询以获取行的排名,与该行与其他行的votes
数相比?
+----+---------+--------+---------------------+
| id | post_id | votes | date |
+----+---------+--------+---------------------+
| 1 | 1 | 10342 | 2015-04-29 04:40:51 |
| 2 | 2 | 9432 | 2015-04-17 22:37:53 |
| 3 | 3 | 33064 | 2015-05-17 22:37:17 |
| 4 | 4 | 32741 | 2015-05-17 22:37:25 |
| 5 | 5 | 30362 | 2015-05-17 22:37:31 |
| 6 | 6 | 15321 | 2015-06-28 00:33:20 |
| 7 | 1 | 4356 | 2015-06-28 00:19:30 |
+----+---------+--------+---------------------+
例如,如果我想在每个月找到post_id
#1的等级,它应该返回如下内容:
+----+------+---------+-------+---------------------+
| id | rank | post_id | votes | date |
+----+------+---------+-------+---------------------+
| 1 | 1 | 1 | 10342 | 2015-04-29 04:40:51 |
| 7 | 2 | 1 | 4356 | 2015-06-28 00:19:30 |
+----+------+---------+-------+---------------------+
这是因为post_id
#1在一年中的第四个月票数最多,但是在今年第六个月中票数第二高。
如何进行此查询?
答案 0 :(得分:0)
SELECT YEAR(t1.date) AS year, MONTH(t1.date) AS month, SUM(IF(t1.votes >= t2.votes, 1, 0)) AS rank
FROM YourTable AS t1
JOIN YourTable AS t2 ON YEAR(t1.date) = YEAR(t2.date) AND MONTH(t1.date) = MONTH(t2.date)
WHERE t2.post_id = 1
GROUP BY year, month