简体   繁体   English

如何计算表中user_id的次数?

[英]How to count the number of times a user_id is in a table?

Consider the following MySQL table: 考虑下面的MySQL表:

user_id
-------
1
1
2
3
3
3
3

I would like an output of: 我想要一个输出:

user_id  cnt
-------------
1        2
2        1
3        4

I though this would make that happen, but it doesn't: 我虽然可以做到这一点,但事实并非如此:

SELECT user_id, COUNT(1) FROM table GROUP BY user_id

What am I doing wrong? 我究竟做错了什么?

SELECT user_id, COUNT(*) FROM table GROUP BY user_id;

btw, there is also the curiosity: 顺便说一句,还有好奇心:

SELECT user_id, SUM(1) FROM table GROUP BY user_id

Both will give you the output you want. 两者都会为您提供所需的输出。

Try this: 尝试这个:

SELECT user_id, COUNT(user_id) as cnt FROM table GROUP BY user_id 从表GROUP BY user_id中以cnt的形式选择user_id,COUNT(user_id)

SELECT user_id, count(user_id) as total FROM temp group by user_id; 

The query produced this. 查询产生了这个。

user_id  total
-------------
1        2
2        1
3        4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM