Skip to content
Advertisement

I want to fetch 2 records with same id

Id  user_id   Name
--- --------  ------
1      1        A
2      1        B
3      1        C
4      2        D
5      2        E
6      2        F

This is my user table and i want to fetch 2 rows in descending using user_id. I want output like.

Id  user_id   Name
--- --------  ------
2      1        B
3      1        C
5      2        E
6      2        F

Thanks in advance

Advertisement

Answer

I think you strictly need an ANCIer approach. You should try below co-related sub query –

SELECT Id, user_id, Name
FROM  T T2
WHERE (SELECT  COUNT(*)
       FROM    T T3
       WHERE T2.user_id = T3.user_id
       AND T2.Id <= T3.Id) <= 2

Fiddle.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement