简体   繁体   中英

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:

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...

If you want the number of clients for each code id You should do the inverse

    SELECT CodeID codes , COUNT(DISTINCT ClientID) clients 
    FROM Entry 
    GROUP BY codes ORDER BY Codes

With one more 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM