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

Jako
  • 4,731
  • 7
  • 39
  • 54
  • People interested in counting distinct rows on several columns (e.g. with wildcard `*`) should check [this answer](https://stackoverflow.com/a/20620693/812102). – Skippy le Grand Gourou Sep 02 '19 at 10:50

4 Answers4

88

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.

Taryn
  • 242,637
  • 56
  • 362
  • 405
  • @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? – Irfan Ahmed Jun 08 '17 at 11:08
  • In reference to your this answer https://stackoverflow.com/questions/12789396/how-to-get-multiple-counts-with-one-sql-query/12789493#12789493 but I need to select it as distinct like above. – Irfan Ahmed Jun 08 '17 at 11:11
  • @IrfanAhmed Off hand I'm not sure. I'd say post a new question with your requirements so it could be answered. – Taryn Jun 12 '17 at 13:53
3
select user_id, count(distinct video_id) from TABLE group by user_id;
Trenton Trama
  • 4,890
  • 1
  • 22
  • 27
2

For total count...

select distinct count(video_id) from Table
where...
group...
aksu
  • 5,221
  • 5
  • 24
  • 39
user3242558
  • 105
  • 1
  • 9
  • 1
    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. – bazeusz Jul 23 '19 at 08:48
  • This will not return distinct - but will return count - this is an erroneous answer – TV-C-1-5 Apr 18 '22 at 01:55
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;
bazeusz
  • 564
  • 4
  • 11