sql计算2个值共享第三个值的次数

时间:2016-04-29 23:19:43

标签: mysql

我有2个表,我可以加入一个共同的id。但是,一个表有人名,另一个表有公司名。

people table

company table

如何生成查询结果,我可以计算每个人与每个公司共享相同ID的次数?

1 个答案:

答案 0 :(得分:0)

你的桌子数据看起来很奇怪。但是这里去了

SELECT p.person,COUNT(*) as share_count
FROM people p
INNER JOIN company c
ON c.id = p.id
GROUP BY p.person

结果

person  share_count
dave    3
mark    4
sara    3

http://sqlfiddle.com/#!9/aba04/3

如果您想按p.id和p.person分组

SELECT p.id,p.person,COUNT(*) as share_count
FROM people p
INNER JOIN company c
ON c.id = p.id
GROUP BY p.id,p.person

结果

id  person  share_count
1   dave    1
1   sara    1
2   mark    2
2   sara    2
3   dave    2
3   mark    2

http://sqlfiddle.com/#!9/aba04/5

更新将share_count除以(不同人的COUNT)

SELECT p.person,COUNT(*) as share_count,COUNT(*)/(SELECT COUNT(DISTINCT person) FROM people) as percent
FROM people p
INNER JOIN company c
ON c.id = p.id
GROUP BY p.person