首页 文章

如何根据多个分组进行计数

提问于
浏览
-2

我正在努力寻找获得这些重要性的最简单方法 .

表结构

GroupId,EventId,UserId,TypeId
100,1,1,1
100,2,1,1
100,1,1,0
100,1,3,0
101,1,1,1

Group有1对多的Event .
1-n事件可以链接到组

1)用户1是typeid 1的唯一用户的组的计数(每组可以是多个事件,所有必须是类型1)

2)用户1是typeid 0的唯一用户的组的计数(每组可以是多个事件,所有必须是类型0)

3)用户1不是typeid 1的唯一用户的组的计数(每组可以是多个事件,所有必须是类型1)

4)用户1不是typeid 0的唯一用户的组的计数(每组可以是多个事件,所有必须是0)

1 回答

  • 2

    你可以使用count(case when)来解决这个问题 .

    select count(case when t2.cn=1 and t1.UserId = 1 and t1.TypeId =1 then 1 else null end) as case1,
           count(case when t2.cn=1 and t1.UserId = 1 and t1.TypeId =0 then 1 else null end) as case2,
           count(case when t2.cn>1 and t1.UserId = 1 and t1.TypeId =1 then 1 else null end) as case3,
           count(case when t2.cn>1 and t1.UserId = 1 and t1.TypeId =1 then 1 else null end) as case4
     from table1 t1
     join (select count(distinct UserId) as cn, TypeId, from table) t2
     on  t1.TypeId = t2.TypeId
    

    在计数(大小写的情况下),然后1表示它将计数,null将不计数 . 所以你只需要弄清楚它应该算什么情况就可以了 .

相关问题