46
+----------+----------+
| user_id  | video_id |
+----------+----------+
|        1 |    1     |
|        1 |    1     |
|        1 |    2     |
|        2 |    1     |
|        2 |    2     |
+----------+----------+

I have a table setup similar to the one above. I would like to return a total count from my query.

For each user_id they need to have a DISTINCT video_id. So above, user_id = 1 would have 2 unique video_id's and user_id = 2 would have 2 unique video_id's. This would make the total 4. I'm not sure the best way to organize my query to achieve the desired result.

Basically for each user_id, I need something like, COUNT(DISTINCT video_id)

I would like the final result just to return total count of everything.

1
  • People interested in counting distinct rows on several columns (e.g. with wildcard *) should check this answer. Commented Sep 2, 2019 at 10:50

4 Answers 4

95

If you want to get the total count for each user, then you will use:

select user_id, count(distinct video_id)
from data
group by user_id;

Then if you want to get the total video_ids then you will wrap this inside of a subquery:

select sum(cnt) TotalVideos
from
(
  select user_id, count(distinct video_id) cnt
  from data
  group by user_id
) d

See SQL Fiddle with Demo of both.

The first query will give you the result of 2 for each user_id and then to get the total of all distinct video_ids you sum the count.

Sign up to request clarification or add additional context in comments.

3 Comments

@bluefeet On a side note, what if we have another column say audio_id and we want to get count of it too in the same query?
In reference to your this answer stackoverflow.com/questions/12789396/… but I need to select it as distinct like above.
@IrfanAhmed Off hand I'm not sure. I'd say post a new question with your requirements so it could be answered.
4
select user_id, count(distinct video_id) from TABLE group by user_id;

2 Comments

Is there a way to return just a total count rather than each users count?
Yes, and I believe bluefeet answered that very well for you.
2

For now a total count of unique user_id, video_id pairs can be calculated with the following query

select count(distinct user_id, video_id) from table;

Comments

1

For total count...

select distinct count(video_id) from Table
where...
group...

2 Comments

I know it's old but just for correctness the above will not return total count of unique values as asked in the original question.
This will not return distinct - but will return count - this is an erroneous answer

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.