简体   繁体   中英

How to select the last record of each ID

I need to extract the last records of each user from the table. The table schema is like below.

mytable

product | user_id |
-------------------
   A    |   15    |
   B    |   15    |
   A    |   16    |
   C    |   16    |
-------------------

The output I want to get is

product | user_id |
-------------------
   B    |   15    |
   C    |   16    |

Basically the last records of each user.

Thanks in advance!

You can use a window function called ROW_NUMBER .Here is a solution for you given below. I have also made a demo query in db-fiddle for you. Please check link Demo Code in DB-Fiddle

WITH CTE AS
(SELECT product, user_id,
       ROW_NUMBER() OVER(PARTITION BY user_id order by product desc)
       as RN
FROM Mytable)
SELECT product, user_id FROM CTE WHERE RN=1 ;

There is no such thing as a "last" record unless you have a column that specifies the ordering. SQL tables represent unordered sets (well technically, multisets).

If you have such a column, then use distinct on :

select distinct on (user_id) t.*
from t
order by user_id, <ordering col> desc;

Distinct on is a very handy Postgres extension that returns one row per "group". It is the first row based on the ordering specified in the order by clause.

You can try using row_number()

select product,iserid
from
(
select product, userid,row_number() over(partition by userid order by product desc) as rn
from tablename
)A where rn=1

You should have a column that stores the insertion order. Whether through auto increment or a value with date and time.

Ex:

autoIncrement produt user_id
1 A 15
2 B 15
3 A 16
4 C 16
SELECT produt, user_id FROM table inner join 
     ( SELECT MAX(autoIncrement) as id FROM table group by user_id ) as table_Aux
     ON table.autoIncrement = table_Aux.id
     

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM