如何在分组中获得MySQL计数

时间:2015-03-17 23:24:08

标签: 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;

1 个答案:

答案 0 :(得分:1)

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