MYSQL-按分组计数

时间:2019-03-15 20:11:48

标签: mysql group-by count

假设这样的表

domain       | city      | number
-------------|-----------|-------
example.com  | rome      | 11111 <--,
example1.com | rome      | 11111    |_ this two should be counted as 1
example2.com | rome      | 11111    |
example.com  | rome      | 11111 <--'
example.com  | amsterdam | 11111
example2.com | rome      | 22222
example.com  | uk        | 22222
example.com  | amsterdam | 22222 <--._ this two should be counted as 1
example.com  | amsterdam | 22222 <--'

我想输出类似以下结果11111, total = 422222, total = 3

到目前为止,我有这个查询,但是当然无法正常工作! :(

SELECT number, COUNT(number) as total FROM table GROUP BY city, domain

2 个答案:

答案 0 :(得分:1)

您可以在经过预处理的表表达式上使用COUNT(),以消除重复,如:

select number, count(*)
from (
  select distinct domain, city, number from my_table
) x
group by number

答案 1 :(得分:1)

您可以group by number

select number, count(distinct concat(domain, '-', city)) total
from tablename
group by number

结果:

number  total
11111   4
22222   3