1

Similar question to this however I want to count how many different distinct values appear for one user_id. If I had the following table:

USER_ID  DATA
123      abc
234      abc
123      def
456      def
123      abc

I would want the following results:

USER_ID  COUNT
123      2
234      1
456      1

Because '123' has both 'abc' and 'def' data values, where as '234' and '456' only have the one distinct data value.

Currently I have the following pseudo-code:

rows = SELECT DISTINCT user_id FROM table
for for in rows:
     result = SELECT DISTINCT user_id, data FROM table WHERE user_id = <row>
     if result.rowcount > 2:
          doSomething()

But this takes a long time as it has to make a call for each user_id.

Can this be done in one MySQL command?

0

3 Answers 3

3

Just use COUNT() aggregation along with GROUP BY

SELECT
    user_id,
    COUNT(DISTINCT data) AS distinct_data_count
FROM table
GROUP BY user_id
Sign up to request clarification or add additional context in comments.

Comments

0

I'm a little rusty, but can't you do

SELECT DISTINCT user_id, COUNT(DISTINCT data) as dc from table;

Comments

0

This is SQL Fiddle

select user_id, count(distinct dat) from test
group by user_id

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.