[英]SQL Getting count of distinct rows for each value
I don't have much experience to SQL, and I can't seem to figure out this problem. 我对SQL没有多少经验,我似乎无法弄清楚这个问题。
If I have a table like this: 如果我有这样的表格:
Installs 安装
id user
1 bob
2 carl
2 carl
2 charles
3 bill
3 bill
and another like this: 和另一个这样的:
Apps 应用
id name
1 app1
2 app2
3 app3
How would I get something like this?: 我怎么会得到这样的东西?:
name distinct_users
app1 1
app2 2
app3 1
I have tried this: 我试过这个:
select apps.name, count(distinct installs.user)
from installs, apps
where installs.id = apps.id;
but that only yields one row because it is counting the total number of distinct users in installs. 但这只会产生一行,因为它计算的是安装中不同用户的总数。
app1 4
You are missing a group by
clause to get result per app : 您缺少group by
子句来获取每个应用的结果:
SELECT apps.name, COUNT(distinct installs.user)
FROM installs, apps
WHERE installs.id = apps.id;
GROUP BY apps.name
Note, by the way, the implicit joins (having more than one table in the from
clause have been considered to be deprecated for quite a while now. Instead, it's recommended you use an explicit join: 顺便提一下,请注意,隐式连接(在from
子句中有多个表已被认为已经弃用了很长一段时间。相反,建议您使用显式连接:
SELECT apps.name, COUNT(distinct installs.user)
FROM installs
JOIN apps ON installs.id = apps.id;
GROUP BY apps.name
Use group by and count(*) 使用group by和count(*)
Select apps.name, count(*)
from installs
inner join apps on installs.id = apps.id
group by apps.name;
You need to add the GROUP BY
. 您需要添加GROUP BY
。
More over avoid comma separated table concepts and use JOIN with ON. 更多的是避免使用逗号分隔的表概念并将JOIN与ON一起使用。
Add alias name for each table to the better readability. 为每个表添加别名以提高可读性。
SELECT A.name, COUNT(DISTINCT I.user)
FROM apps A
INNER JOIN installs I ON I.id = A.id
GROUP BY A.name;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.