[英]MySQL Select Distinct Count
+----------+----------+
| 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
. 对于每个
user_id
他们需要有一个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. 所以上面,
user_id = 1
将具有2个唯一的video_id,而user_id = 2
将具有2个唯一的video_id。 This would make the total 4. I'm not sure the best way to organize my query to achieve the desired result. 这将使总数达到4.我不确定组织查询以获得所需结果的最佳方法。
Basically for each user_id, I need something like, COUNT(DISTINCT video_id)
基本上对于每个user_id,我需要像
COUNT(DISTINCT video_id)
这样的东西COUNT(DISTINCT video_id)
I would like the final result just to return total count of everything. 我希望最终的结果只是为了返回所有内容的总数。
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: 然后,如果你想获得总video_ids,那么你将把它包装在子查询中:
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. 请参阅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. 第一个查询将为每个
user_id
提供2
的结果,然后获得所有不同video_ids的总和,并将计数总和。
select user_id, count(distinct video_id) from TABLE group by user_id;
For total count... 总计数......
select distinct count(video_id) from Table
where...
group...
现在,可以使用以下查询计算唯一user_id,video_id对的总计数
select count(distinct user_id, video_id) from table;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.