统计mysql计数的结果?

发布于 2024-12-23 10:29:50 字数 506 浏览 1 评论 0原文

我想知道如何使用 mysql 查询解决以下问题,但真的不知道如何继续我的第一次计数。

在表中有用户 ID 和他们拥有的项目 ID。

user_id | item
--------------
12      | 1
11      | 3
34      | 1
12      | 2
34      | 2
9       | 1
12      | 3

如果我按 user_id 分组并对 user_id 进行计数,我会得到用户列表以及他们赢得了多少项目,例如:

user_id | count(user_id) i.e. how many items have they won
-----------------------
9       | 1
11      | 1
12      | 3
34      | 2

我如何依次计算有多少用户赢得了 1、2 或 3 个项目,即。 count 计数的结果,按user_id的计数分组?

I wonder how the following could be solved with a mysql query, but don't really know how to proceed past my first count.

In a table there is user ids and an item id they have.

user_id | item
--------------
12      | 1
11      | 3
34      | 1
12      | 2
34      | 2
9       | 1
12      | 3

If I group by user_id and count the user_id, I get a list of users and how many items they have won, like:

user_id | count(user_id) i.e. how many items have they won
-----------------------
9       | 1
11      | 1
12      | 3
34      | 2

How can I in turn count how many users have won 1, 2 or 3 items, ie. count the result of the count, grouped by the count of user_id?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

只等公子 2024-12-30 10:29:50

从选择中选择:

select times_won, count(*)
from (
    select user_id, count(*) as times_won
    from my_table
    group by 1
) x
group by 1

Select from the select:

select times_won, count(*)
from (
    select user_id, count(*) as times_won
    from my_table
    group by 1
) x
group by 1
财迷小姐 2024-12-30 10:29:50

也许我不明白这个问题...你不能用这个吗?

SELECT item, COUNT(DISTINCT user_id) 
FROM ...
GROUP BY item

相反,如果您只想对发布的中间结果中的行进行计数,则可以使用如下子查询:

SELECT COUNT(*) FROM (
    SELECT user_id, COUNT(user_id) AS count
    FROM ...
    GROUP BY user_id
) AS intermediate_result
GROUP BY count

Maybe I've not understand the question... Can't you just use this?

SELECT item, COUNT(DISTINCT user_id) 
FROM ...
GROUP BY item

Instead, if you simply want to count rows from the intermediate result you posted, you can use subqueries like this:

SELECT COUNT(*) FROM (
    SELECT user_id, COUNT(user_id) AS count
    FROM ...
    GROUP BY user_id
) AS intermediate_result
GROUP BY count
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文