python - 如何获取MySQL分组内的计数

标签 python mysql

鉴于此表。

+----+-------+-------+
| id | color | grain | 
+----+-------+-------+
|  1 |   A   |   B   |
|  1 |   A   |   B   |
|  1 |   A   |   B   |
|  2 |   B   |   X   |
|  2 |   B   |   X   |
|  2 |   B   |   Z   |
|  2 |   E   |   E   |
|  3 |   A   |   C   |
|  3 |   A   |   B   |
|  3 |   A   |   B   |
+----+-------+-------+

产生以下结果的 MySQL 查询是什么。 我需要计算每个 id 中颜色/颗粒组合的唯一出现次数。

+----+-------+-------+-------------------+
| id | color | grain | color/grain count |
+----+-------+-------+-------------------+
|  1 |   A   |   B   |         1         |
|  2 |   B   |   X   |         3         |
|  2 |   B   |   Z   |         3         |
|  2 |   E   |   E   |         3         |
|  3 |   A   |   C   |         2         |
|  3 |   A   |   B   |         2         |
+----+-------+-------+-------------------+

这是我当前的查询,但它不会产生我正在寻找的计数。计数是针对 group by 子句的出现次数,而不是 id 中的唯一出现次数。

select id,color,grain,count(id)
  from table
group by id,color,grain
order by id;

最佳答案

select  id,
        color,
        grain,
        count(*) 
    from table
    group by id, color, grain

产生这个:

id  color   grain   count
1   A       B       3
2   B       X       2
2   B       Z       1
2   E       E       1
3   A       B       2
3   A       C       1

差不多就到了。现在您需要更改它以按 id 显示不同记录的数量,因此我们可以通过使用子查询来做到这一点:

select  x.id,
        COUNT(*)
    from (
        select  id,
                color,
                grain,
                COUNT(*) cnt
            from #table
            group by id, color, grain
        ) x
    group by x.id

结果是:

id  count
1   1
2   3
3   2

现在,要获得扩展结果,请加入:

select a.id, a.color, a.grain, b.cnt
    from (
        select  id,
                color,
                grain,
                COUNT(*) cnt
            from #table
            group by id, color, grain
        ) a
    join (
        select  x.id,
                COUNT(*) cnt
            from (
                select  id,
                        color,
                        grain,
                        COUNT(*) cnt
                    from #table
                    group by id, color, grain
                ) x
            group by x.id
        ) b on
        a.id = b.id

结果是:

id  color   grain   cnt
1   A       B       1
2   B       X       3
2   B       Z       3
2   E       E       3
3   A       B       2
3   A       C       2

关于python - 如何获取MySQL分组内的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29111546/

相关文章:

php - 在 PHP mySql 中按频率排序关键字

python - 稳健且可自动化的液滴拟合

python - 如何在 python 中扩展 Kafka Consumers?

python - PythonAnywhere 上带有 Web.py 的 Web 表单

python - SGDRegressor() 不断地不提高验证性能

mysql - 如何解决 mysql 线程堆栈溢出问题?

php - 我的 PHP 函数不工作

php - 尝试使用复选框将评论定义为私有(private)或非私有(private)。使用 AJAX 发布到 PHP MySQL

c# - 如何在分组时查找行数

python - 数据类型 float32 for attr 'T' 不在允许值列表中 : int32, int64