Search code examples
sqloraclegreatest-n-per-group

i want to get the pid of picture having maximum likes. how can i do that?


I have tried this

select max(c) from (select pid as p, count(likeuid) as c from likes group by pid);

But this gives me only the count of picture which is liked most. I want pid of the picture which is liked most.

this is my mini instadb database tables description

likes table

CREATE TABLE  "LIKES" 
   (    "PID" NUMBER(6,0) NOT NULL ENABLE, 
    "LIKEUID" NUMBER(6,0) NOT NULL ENABLE, 
    "COMMENTS" VARCHAR2(140) NOT NULL ENABLE, 
     CONSTRAINT "LIKES_UK1" UNIQUE ("PID", "LIKEUID", "COMMENTS") ENABLE
   ) ;ALTER TABLE  "LIKES" ADD CONSTRAINT "LIKES_FK2" FOREIGN KEY ("PID")
      REFERENCES  "PICTURES" ("PID") ON DELETE CASCADE ENABLE;ALTER TABLE  "LIKES" ADD CONSTRAINT "LIKES_FK3" FOREIGN KEY ("LIKEUID")
      REFERENCES  "USERS" ("USERID") ON DELETE CASCADE ENABLE;

Solution

  • The following query worked for me

    select pid from likes group by pid having count(pid)=(select max(count(pid)) from likes group by pid);