计算未发生特定事件的用户

时间:2019-02-04 19:20:58

标签: sql postgresql

您好,下表

id     event
 1   unknown
 1   unknown
 1   unknown
 2   unknown
 2         X
 2         Y
 3   unknown
 3   unknown
 4         X
 5         Y

我想计算所有用户行中所有值未知的值

在这种情况下,它们应该是5个中的2个

我的尝试是:

select 
   count(distinct case when event != 'unknown' then id else null end) as loggeds,
   count(distinct case when event = 'unknown' then id else null end) as not_log_android,
   count(distinct event) as session_long
from table

但是完全错误

4 个答案:

答案 0 :(得分:1)

不存在:

select t.id
from tablename as t
where not exists (
  select 1 from tablename where id = t.id and event <> 'unknown'
)
group by t.id

有关不同ID的数量:

select count(distinct t.id)
from tablename as t
where not exists (
  select 1 from tablename where id = t.id and event <> 'unknown'
)

请参见demo

答案 1 :(得分:1)

您可以检查以下问题:How to check if value exists in each group (after group by)

SELECT COUNT(DISTINCT t1.id)
FROM theTable t1
WHERE NOT EXISTS (SELECT 1 from theTable t2 where t1.id = t2.id and t2.value != 'unknown')

OR

SELECT COUNT(t.id)
FROM theTable t
GROUP BY t.id
HAVING MAX(CASE value WHEN 'unknown' THEN 0 ELSE 1 END) = 0

答案 2 :(得分:0)

SELECT id
FROM YourTable
GROUP BY id
HAVING COUNT(*) = COUNT ( CASE WHEN event = 'unknown' THEN 1 END )

答案 3 :(得分:0)

我会进行聚合:

SELECT id
FROM table t
GROUP BY id
HAVING MIN(event) = MAX(event) AND MIN(event) = 'unknown';