[英]How to Count Distinct for two columns in MYSQL
I have a table with Entries from Participants with multiples Codes and I want to group them by how many Participants used how many distinct Codes. 我有一个表格,其中有来自参与者的带有多个代码的条目,并且我想按多少参与者使用多少个不同代码来对它们进行分组。
This is my table 这是我的桌子
| CodeID | ClientID |
--------------------
| 1 | 36 |
| 1 | 36 |
| 2 | 36 |
| 3 | 36 |
| 10 | 36 |
| 9 | 36 |
| 3 | 36 |
| 2 | 36 |
| 1 | 38 |
| 1 | 39 |
| 1 | 40 |
| 2 | 40 |
| 3 | 40 |
| 1 | 41 |
| 2 | 41 |
I tried with Group By and I have half the result I'm looking for, this: 我尝试了Group By,但结果却只有一半:
SELECT COUNT(DISTINCT CodeID) AS Codes, ClientID FROM Entry GROUP BY ClientID ORDER BY Codes
gives me this 给我这个
| Codes | ClientID |
--------------------
| 1 | 38 |
| 1 | 39 |
| 2 | 41 |
| 3 | 40 |
| 5 | 36 |
And the result I'm looking for is this: 我寻找的结果是这样的:
| Codes | Clients |
-------------------
| 1 | 2 |
| 2 | 1 |
| 3 | 1 |
| 5 | 1 |
I don't know if there is a way to do this with multiples GROUP BY or with a subquery... 我不知道是否可以使用GROUP BY的倍数或子查询来执行此操作...
If you want the number of clients for each code id You should do the inverse 如果您想要每个代码ID的客户端数量,则应进行反操作
SELECT CodeID codes , COUNT(DISTINCT ClientID) clients
FROM Entry
GROUP BY codes ORDER BY Codes
With one more GROUP BY. 还有一个GROUP BY。
SELECT cnt, count(CodeID)
FROM ( SELECT CodeID, count(distinct ClientID) cnt
FROM Entry
GROUP BY CodeID
) T
GROUP BY cnt
With your answers I edited my code to make it work, thanks a lot! 有了您的回答,我编辑了代码以使其正常运行,非常感谢!
SELECT Codes, COUNT(ClientID) AS Clients
FROM ( SELECT COUNT(DISTINCT CodeID) AS Codes, ClientID
FROM Entry
GROUP BY ClientID) Result
GROUP BY Codes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.