我有以下SQL表:
user_id | device | num_uses
---------------------------
1 | phone | 10
1 | tv | 5
2 | phone | 15
3 | tv | 45
我想提出一个查询,它会返回每台设备的用户数量,还会返回唯一身份用户的总数。
是否可以使用一个查询执行此操作,或者是我唯一的选项来创建2个查询,一个用于每个设备的用户数,另一个用于获取不同数量的用户?
我必须按设备获取用户数的查询是:
select count(user_id), device from usage group by device;
给了我:
count | device
---------------
2 | phone
2 | tv
预期结果将是:
category_count | device | total_distinct_users
------------------------------------------------
2 | phone | 3
2 | tv | 3
答案 0 :(得分:1)
你想要count(distinct)
。我想是这样的:
select device, sum(uses) as num_uses, count(*) as num_users,
count(distinct user_id) as num_distinct_users
from usage
group by device;
编辑:
如果您想要每台设备的用户数和唯一身份用户总数,那么您可能需要:
select u.device, count(*) as num_users,
uu.num_distinct_users
from usage u cross join
(select count(distinct user_id) as num_distinct_users from usage) uu
group by device, uu.num_distinct_users;
答案 1 :(得分:0)
我的猜测是,您希望将count
与distinct
包括在一起:
select count(user_id),
count(distinct user_id),
device
from usage
group by device
答案 2 :(得分:0)
尝试:
SELECT COUNT(DISTINCT user_id), device
FROM `usage`
GROUP BY device
答案 3 :(得分:0)
我们也可以通过以下方式实现:
SELECT u.device,
COUNT(u.user_id) category_count,
MAX(t.tot) total_distinct_users
FROM #usage u
OUTER APPLY(SELECT COUNT(DISTINCT USER_ID) tot FROM #usage) t
GROUP BY device