Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select unique rows only in sql?

I have two columns, senderUserID and recieverUserID in Messages table. I select senderUserID and recieverUserID where current receiver sent a message to current sender in the past. I select 10 rows only each time but sometimes in this table senderUserID appears more than once when i need that only senderUserID will be unique, while recieverUserID can return as many times as it happens.

this is sample data

66622   61350
90166   79222
90176   79222
86727   80452
10888   47305
66560   79219
66622   80452
89548   14452
66622   69177
52081   79223

as you can see 66622 appears twice in senderUserID. How do i limit it to appears only once.

thanks

like image 616
eugeneK Avatar asked Feb 26 '26 20:02

eugeneK


1 Answers

;WITH cte AS
(
SELECT senderUserID, 
       recieverUserID,
       ROW_NUMBER() OVER (PARTITION BY senderUserID ORDER BY recieverUserID) AS RN
FROM YourTable
)
SELECT senderUserID,recieverUserID FROM cte 
WHERE RN=1
like image 121
Martin Smith Avatar answered Mar 01 '26 10:03

Martin Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!