Mysql 每列行计数器
假设我有一张这样的桌子Mysql 每列行计数器,mysql,Mysql,假设我有一张这样的桌子 | id | user_id | event_id | created_at | |----|---------|----------|------------| | 1 | 5 | 10 | 2015-01-01 | | 2 | 6 | 7 | 2015-01-02 | | 3 | 3 | 8 | 2015-01-01 | | 4 | 5 | 9 | 2015-
| id | user_id | event_id | created_at |
|----|---------|----------|------------|
| 1 | 5 | 10 | 2015-01-01 |
| 2 | 6 | 7 | 2015-01-02 |
| 3 | 3 | 8 | 2015-01-01 |
| 4 | 5 | 9 | 2015-01-04 |
| 5 | 5 | 10 | 2015-01-02 |
| 6 | 6 | 1 | 2015-01-01 |
我希望能够为每个用户生成事件计数器。因此,我的结果是:
| counter | user_id | event_id | created_at |
|---------|---------|----------|------------|
| 1 | 5 | 10 | 2015-01-01 |
| 1 | 6 | 7 | 2015-01-02 |
| 1 | 3 | 8 | 2015-01-01 |
| 2 | 5 | 9 | 2015-01-04 |
| 3 | 5 | 10 | 2015-01-02 |
| 2 | 6 | 1 | 2015-01-01 |
一个想法是自联接表并分组,以复制上面的行数。。其他RDBMS中提供的功能 选中此项并查看第二个查询,以了解在这种情况下内部联接是如何工作的
select t1.user_id,
t1.event_id,
t1.created_at,
count(*) as counter
from your_table t1
inner join your_table t2
on t1.user_id=t2.user_id
and t1.id>=t2.id
group by t1.user_id,
t1.event_id,
t1.created_at
order by t1.user_id,t1.event_id;
输出:
+---------+----------+------------+---------+
| user_id | event_id | created_at | counter |
+---------+----------+------------+---------+
| 3 | 8 | 01-01-2015 | 1 |
| 5 | 10 | 01-01-2015 | 1 |
| 5 | 10 | 02-01-2015 | 3 |
| 5 | 9 | 04-01-2015 | 2 |
| 6 | 1 | 01-01-2015 | 2 |
| 6 | 7 | 02-01-2015 | 1 |
+---------+----------+------------+---------+
请尝试以下操作:
select counter,
xx.user_id,
xx.event_id,
xx.created_at
from xx
join (select a.id,
a.user_id,
count(*) as counter
from xx as a
join xx as b
on a.user_id=b.user_id
and b.id<=a.id
group by 1,2) as counts
on xx.id=counts.id
使用联接为每个id生成行,并对其下方的用户的所有其他较低id进行计数。尝试以下操作:
子查询将有助于获得此结果
select (select count(*) from user_event iue where iue.user_id == oue.user_id) as counter,
oue.user_id,
oue.event_id,
oue.created_at
from user_event oue
您可以尝试将变量用作表,将其与源表交叉连接,并在用户id更改时重置
SELECT @counter := CASE
WHEN @user = user_id THEN @counter + 1
ELSE 1
END AS counter,
@user := user_id AS user_id,
event_id,
created_at
FROM your_table m,
(SELECT @counter := 0,
@user := '') AS t
ORDER BY user_id;
我已经创建了一个演示您是否尝试过按查询分组?你应该先表现出你解决问题的努力。分组是行不通的。它会告诉我总数。不是柜台。好的,我知道了。我不确定你想要什么是很容易使用SQL实现的。最好返回原始数据,然后在应用程序中进行处理。您能解释一下计数器的计数吗?在您的示例中,用户6有2个事件,为什么计数器是2和3?用户触发的事件数的运行计数器。假设我想具体查看用户触发的前10个事件的列表,这应该会很容易。修正了这个例子。对不起。。我的例子被编辑了。我修好了。我不确定我是否了解您的查询工作原理。请检查更新的答案。查看Rextester演示,并查看第二个查询以了解其工作原理。