我正在开发一个拍卖应用程序,其中出价以下列格式保存在表格中:
id | user_id | auction_id | placed_at
我想按用户ID对出价进行分组并选择其计数,但前提是用户ID一个接一个地出现。出价按placement_at降序排序。这就是我的意思:
1 | 1 | 1 | 01-04-2010 00:00:06
2 | 1 | 1 | 01-04-2010 00:00:05
3 | 2 | 1 | 01-04-2010 00:00:04
4 | 2 | 1 | 01-04-2010 00:00:03
5 | 3 | 1 | 01-04-2010 00:00:02
6 | 2 | 1 | 01-04-2010 00:00:01
在这种情况下,我应该得到:
count | user_id | auction_id
2 | 1 | 1
2 | 2 | 1
1 | 3 | 1
1 | 2 | 1
我怎样才能达到这个效果?结果将用于生成拍卖的活动流,因此它们将用于生成字符串,例如“John Smith对此次拍卖的出价2次”。该应用程序是使用Ruby on Rails构建的,如果有帮助的话。
提前谢谢。
答案 0 :(得分:1)
SELECT user_id, auction_id, COUNT(*)
FROM (
SELECT @r := @r + CASE WHEN @user_id = user_id AND @auction_id = auction_id THEN 0 ELSE 1 END AS _g,
user_id, auction_id,
@user_id := user_id,
@auction_id := auction_id
FROM (
SELECT @r := 0,
@user_id := NULL,
@auction_id := NULL
) vars,
mytable
ORDER BY
auction_id DESC, placed_at DESC
) q
GROUP BY
user_id, auction_id, _g
ORDER BY
_g