我有一个带有userid和timestamp的简单事件表。每一行都是执行事件的用户:
+--------+---------------+
| userid | timestamp |
+--------+---------------+
| 3 | 5/25/14 23:30 |
| 2 | 5/25/14 20:57 |
| 1 | 5/25/14 20:18 |
| 2 | 5/25/14 18:49 |
| 2 | 5/25/14 13:41 |
| 1 | 5/25/14 5:47 |
| 3 | 5/24/14 22:34 |
| 1 | 5/24/14 22:07 |
| 2 | 5/24/14 21:53 |
| 1 | 5/24/14 21:42 |
+--------+---------------+
我想添加/选择一个列,其中包含我之前在EACH行中看过用户的次数。所以预期的输出是:
+--------+---------------+-------+
| userid | timestamp | count |
+--------+---------------+-------+
| 3 | 5/25/14 23:30 | 2 |
| 2 | 5/25/14 20:57 | 4 |
| 1 | 5/25/14 20:18 | 4 |
| 2 | 5/25/14 18:49 | 3 |
| 2 | 5/25/14 13:41 | 2 |
| 1 | 5/25/14 5:47 | 3 |
| 3 | 5/24/14 22:34 | 1 |
| 1 | 5/24/14 22:07 | 2 |
| 2 | 5/24/14 21:53 | 1 |
| 1 | 5/24/14 21:42 | 1 |
+--------+---------------+-------+
例如,从顶部开始的第三行表示我已经看到用户1总共四次,包括当前的一次。计数为1的底行意味着我只看过一次用户1(这是第一次)。
有没有办法在mysql中进行这种类型的计数?谢谢!
答案 0 :(得分:2)
SELECT userid, timestamp,
(SELECT COUNT(*) FROM myTable t2
WHERE t2.userid = t1.userid
AND t2.timestamp <= t1.timestamp) AS user_count
FROM myTable t1
我知道你要求提供一个没有小组的查询,但无论如何都要在这里查询:)
SELECT t1.userid, t1.timestamp, COUNT(*)
FROM myTable t1
JOIN myTable t2 ON t1.userid = t2.userid AND t2.timestamp <= t1.timestamp
GROUP BY t1.userid, t1.timestamp
答案 1 :(得分:2)
您也可以使用排名查询
SELECT
userid,
`timestamp`,rank FROM(
SELECT
userid,
`timestamp`,
@r:= CASE WHEN userid = @g THEN @r+1 ELSE @r:=1 END rank
,@g:=userid
FROM t,(SELECT @r:=0,@g:=0) t1
ORDER BY userid,timestamp
) t
ORDER BY timestamp DESC