0

I have the following table:

intStudentCode strFavoriteSocialMedia
1 Facebook
1 Instagram
2 Twitter
3 TikTok
4 Youtube
5 Facebook
6 TikTok
6 Youtube

The table has 8 lines. I want a table having only non-repeating intStudentCode. For Example:

intStudentCode strFavoriteSocialMedia
1 Facebook
2 Twitter
3 TikTok
4 Youtube
5 Facebook
6 TikTok

I dont have preference if the strFavoriteSocialMedia for intStudentCode = 1 is Facebook or Instagram. The same to intStudentCode = 6. All I want is retrieve a single student line based on intStudentCode. PS: I am using SQL Server 2012, but if you have the solution for another DBMS, it also help.

1

2 Answers 2

4

Since you don't have a preference if the strFavoriteSocialMedia a simple aggregation should do the trick

Select intStudentCode
      ,strFavoriteSocialMedia = max( strFavoriteSocialMedia )
 From  YourTable
 Group By intStudentCode

Or another option using WITH TIES in concert with row_number()

Select top 1 with ties *
 From  YourTable
 Order By row_number() over (partition by intStudentCode order by strFavoriteSocialMedia)
Sign up to request clarification or add additional context in comments.

1 Comment

You're awesome, It works!! Thanks a lot!!
0

To add-up, Another way that would help using Row_Number

SELECT intStudentCode,strFavoriteSocialMedia  FROM (
SELECT ROW_NUMBER() OVER(PARTITION BY intStudentCode ORDER BY strFavoriteSocialMedia) as r,* 
FROM Table
)TEMP WHERE r=1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.