首先按用户排序数据库结果集,然后按日期排序

时间:2012-04-11 16:36:27

标签: mysql sql

考虑下表(“推文”):

+---------+------------+----------+
| user_id | _date      | tweet_id |
+---------+------------+----------+
| 1       | 2011-03-17 | 12       |
| 1       | 2011-03-17 | 16       |
| 1       | 2011-01-18 | 17       |
| 2       | 2011-03-18 | 23       |
| 2       | 2011-01-17 | 29       |
| 2       | 2011-03-17 | 32       |
| 2       | 2011-01-17 | 33       |
| 2       | 2011-03-18 | 34       |
| 2       | 2011-01-19 | 45       |
| 2       | 2011-03-19 | 48       |
| 3       | 2011-01-19 | 50       |
| 3       | 2011-03-19 | 51       |
| 3       | 2011-01-19 | 52       |
| 3       | 2011-01-20 | 53       |
+---------+------------+----------+

我想要以下输出:推文PER用户ORDERED BY日期:

user_id  _date       cnt
------------------------
1        2011-03-17  2
1        2011-03-18  1
2        2011-03-17  3
2        2011-03-18  2
2        2011-03-19  2
3        2011-03-19  3
3        2011-03-20  1

我不明白为什么,但这不起作用:

SELECT user_id, _date, COUNT(tweet_id) AS cnt FROM tweets 
GROUP BY nyse_date ORDER BY sp100_id ASC

有人可以向我解释原因吗?

2 个答案:

答案 0 :(得分:1)

你几乎得到了它。不确定为什么你有nyse_datesp100_id?您需要将user_id_date组合在一起,然后按他们排序。这应该适合你:

SELECT user_id, _date, COUNT(tweet_id) AS cnt FROM tweets 
GROUP BY user_id, _date ORDER BY user_id, _date ASC

答案 1 :(得分:1)

尝试:

SELECT user_id, _date, count(*) AS cnt
FROM tweets
GROUP BY user_id, _date
ORDER BY _date ASC