[英]SQL Getting count of distinct rows for each value
我對SQL沒有多少經驗,我似乎無法弄清楚這個問題。
如果我有這樣的表格:
安裝
id user
1 bob
2 carl
2 carl
2 charles
3 bill
3 bill
和另一個這樣的:
應用
id name
1 app1
2 app2
3 app3
我怎么會得到這樣的東西?:
name distinct_users
app1 1
app2 2
app3 1
我試過這個:
select apps.name, count(distinct installs.user)
from installs, apps
where installs.id = apps.id;
但這只會產生一行,因為它計算的是安裝中不同用戶的總數。
app1 4
您缺少group by
子句來獲取每個應用的結果:
SELECT apps.name, COUNT(distinct installs.user)
FROM installs, apps
WHERE installs.id = apps.id;
GROUP BY apps.name
順便提一下,請注意,隱式連接(在from
子句中有多個表已被認為已經棄用了很長一段時間。相反,建議您使用顯式連接:
SELECT apps.name, COUNT(distinct installs.user)
FROM installs
JOIN apps ON installs.id = apps.id;
GROUP BY apps.name
使用group by和count(*)
Select apps.name, count(*)
from installs
inner join apps on installs.id = apps.id
group by apps.name;
您需要添加GROUP BY
。
更多的是避免使用逗號分隔的表概念並將JOIN與ON一起使用。
為每個表添加別名以提高可讀性。
SELECT A.name, COUNT(DISTINCT I.user)
FROM apps A
INNER JOIN installs I ON I.id = A.id
GROUP BY A.name;
SELECT `apps`.`name`, COUNT(DISTINCT(`installs`.`user`))
FROM `installs`, `apps`
WHERE `installs`.`id` = `apps`.`id`
GROUP BY `apps`.`id`;
看到這個小提琴 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.