gpt4 book ai didi

sql - 如果值存在于多个类别中,如何分隔分组依据

转载 作者:行者123 更新时间:2023-11-29 12:10:27 25 4
gpt4 key购买 nike

我有一个这样的表:

CREATE TEMP TABLE users_category 
(
user_id int,
category_id int
);

insert into users_category (user_id, category_id)
values (100, 1), (100, 2), (103, 4), (105, 4), (106, 2), (107, 1)

然后我尝试计算有多少用户使用以下类别:

select category_id,count(*)
from users_category
group by category_id

响应是:

category_id   count
4 2
1 2
2 2

如果用户存在多个类别,如何添加逻辑,在其他类别中计算。

例如,用户 100 存在于类别 1 和 2 中,我不会为这两个类别计算它。我想添加新类别 ex。 99 并且必须在那里添加用户。

响应必须像这样:

category_id  count
4 2
1 1
2 1
99 1 (user who was in both category)

怎么做?

最佳答案

您需要先在用户级别聚合,然后在类别级别聚合:

select category_id, count(*)
from (select user_id,
(case when min(category_id) = max(category_id) then min(category_id)
else 99
end) as category_id
from users_category uc
group by user_id
) uc
group by category_id;

关于sql - 如果值存在于多个类别中,如何分隔分组依据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38505657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com