如何判断用户表中的is_rh字段是非全是为1或者全是为0或者1或者0都存在的个数

提供靠近解题的都会采纳急!!
需求:用户看了视频就是item_Id,有对应的is_rh,需要统计用户查看的is_rh的值如果全是1,是就统计加1,如果是0也统计,如果存在0或者1的也统计
可以用sql查询,也可以查出来用java代码实现

img

以user_id统计每个用户is_rh为1、0的情况如下:

select 
user_id,
sum(case when is_rh=1 then 1 else 0 end) '为1总数',
sum(case when is_rh=0 then 1 else 0 end) '为0总数'
from 表名
group by user_id

统计所有user_id中全为1、全为0、存在0或1的情况如下:

select sum(case when con1>0 and con0=0 then 1 else 0 end) '全为1',
sum(case when con1=0 and con0>0 then 1 else 0 end) '全为0',
sum(case when con1>0 and con0>0 then 1 else 0 end) '存在1和0'
(
select 
user_id,
sum(case when is_rh=1 then 1 else 0 end) con1,
sum(case when is_rh=0 then 1 else 0 end) con0
from 表名
group by user_id
) item

img

全是1要统计,全是0也要统计,有0有1也要统计,这有啥是不统计的


select user_id,is_rh,count(is_rh) cnt from 表名 group by user_id,is_rh

虽然我不会java和mysql,但我觉得你发的题目过于基础,加点特殊要求吧,要不然人家可能不敢回答,😎


select user_id,sum(is_rh) from table_name
group by user_id

请采纳,十分感谢!
有需要,欢迎随时交流沟通!

太简单了吧 sum(case when ……)函数就解决了

分组就可以了吧,,,
select user_id,count(is_rh) from 表名 group by user_id


select 
user_id,
sum(case when is_rh=1 then 1 else 0 end) '统计1',
sum(case when is_rh=0 then 1 else 0 end) '统计0',
count(1) as '总数'
from 表名
group by user_id

我看了一下前面的回答,发现好像没有人明白题意,那我只能献丑了。

select 
count(case when b.user_id is null then 1 end) flag1,--全是1的用户数
count(case when a.user_id is null then 1 end) flag0,--全是0的用户数
count(case when a.user_id is not null and b.user_id is not null then 1 end) flag1_0--1、0同时存在的用户数
from 
(select distinct user_id from table where is_rh = '1') a
full join
(select distinct user_id from table where is_rh = '0') b
on a.user_id = b.user_id
;

https://blog.csdn.net/boonya/article/details/100063312?spm=1005.2026.3001.5635&utm_medium=distribute.pc_relevant_ask_down.none-task-blog-2~default~OPENSEARCH~Rate-6.pc_feed_download_top3ask&depth_1-utm_source=distribute.pc_relevant_ask_down.none-task-blog-2~default~OPENSEARCH~Rate-6.pc_feed_download_top3ask

是不是直接按用户id分组就可以了

代码如下,望采纳


```java
select 
user_id,
sum(case when is_rh=1 then 1 else 0 end) numOfOne,
sum(case when is_rh=0 then 1 else 0 end) numOfZero,
(sum(case when is_rh=1 then 1 else 0 end)+sum(case when is_rh=0 then 1 else 0 end)) totalNum
from 表名
group by user_id

```