Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group by two fields, and having count() on first field

I have a table that stored users play list, a video can be viewed by multiple users for multiple times. A records goes like this:

videoid, userid, time
123,     abc   , 2013-09-11

It means user(abc) has watched video(123) on 2013-09-11

Now I want to find distinct users watched video list (no duplication), and only show the users that have watched more than two videos.

SELECT videoid, userid 
FROM table_play_list
WHERE SOME CONDICTION
GROUP BY userid, videoid

The sql only select distinct users watchlist, I also want to filter users that have watched more than two different videos.

I know I have to google and read the documentation first, some said 'HAVING' could solve this, unfortunately, I could not make it.

like image 327
蒋艾伦 Avatar asked Sep 11 '13 07:09

蒋艾伦


People also ask

Can count be used with GROUP BY?

SQL – count() with Group By clauseThe count() function with the GROUP BY clause is used to count the data which were grouped on a particular attribute of the table.

Can we use GROUP BY with 2 columns in SQL?

Yes, it is possible to use MySQL GROUP BY clause with multiple columns just as we can use MySQL DISTINCT clause.

Can I GROUP BY 2 columns?

A GROUP BY clause can contain two or more columns—or, in other words, a grouping can consist of two or more columns.


2 Answers

If I understand correctly, you are looking for users who watched more than two different videos. You can do this by using count(distinct) with a partition by clause:

select userid, videoid
from (SELECT userid, videoid, count(distinct videoid) over (partition by userid) as cnt
      FROM table_play_list
      WHERE <ANY CONDITION>
     ) t
where cnt > 2;
like image 197
Gordon Linoff Avatar answered Sep 22 '22 17:09

Gordon Linoff


Try like this,

SELECT userid, count(*)
FROM   table_play_list
--WHERE SOME CONDITION
GROUP BY user_id
having count(*) >2;

Try this if you need to get the count based on userid and videoid(users who watch the same video more than two times).

SELECT userid, videoid, count(*)
FROM   table_play_list
--WHERE SOME CONDITION
GROUP BY user_id, video_id
having count(*) >2;
like image 43
Dba Avatar answered Sep 22 '22 17:09

Dba