Share via

get record from every group

newbie 81 Reputation points
2022-07-25T02:24:51.603+00:00

I have a table-messages that contains some data like blow picture:

224222-image.png
I want to get the follwing result,
224080-image.png

Can someone help me to implement a replacement scheme, I have tried it, it is very inefficient for me, I don't like it very much.
SELECT
*
FROM (SELECT
*
FROM messages
ORDER BY id DESC) AS x
GROUP BY name

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

0 comments No comments

Answer accepted by question author

Bert Zhou-msft 3,521 Reputation points
2022-07-25T02:36:26.68+00:00

Hi,@newbie

Welcome to Microsoft T-SQL Q&A Forum!

Try both options, if you want the record to always be the last in ID order. This will help you.

--first way  
  
select a.*  
from  messages a  
inner join   
(  
  select name, max(id) as maxid from messages group by name  
) b   
  on  a.id = b.maxid  
  
--second way  
  
;WITH CTE AS   
(  
  SELECT Id, Name, OtherColumns,rn=ROW_NUMBER() OVER ( PARTITION BY Name ORDER BY Id )   
  FROM messages  
)  
  SELECT Id, Name, OtherColumns  
  FROM CTE  
  WHERE rn = 1;  

Best regards,
Bert Zhou

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.