【问题标题】:MYSQL - COUNT BY GROUPingMYSQL - 按分组计数
【发布时间】:2019-03-15 20:11:48
【问题描述】:

假设有这样的表格

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

【问题讨论】:

  • 关闭试试COUNT(DISTINCT number)
  • 你的主键是什么?

标签: mysql group-by count


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    你可以group by number:

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

    结果:

    number  total
    11111   4
    22222   3
    

    【讨论】:

    • 不错的方法! ;-)
    猜你喜欢
    • 2012-05-10
    • 1970-01-01
    • 2016-11-26
    • 2011-07-21
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多