鉴于此表。
+----+-------+-------+
| 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/