Hi nedash,
You need to use below query to get distinct Topic record order by Preference asc.
DECLARE @Documentry_Info AS TABLE(TopicId INT,Preference INT,Topic VARCHAR(20))
INSERT INTO @Documentry_Info VALUES(1,1,'Documentry')
INSERT INTO @Documentry_Info VALUES(5,1,'ab')
INSERT INTO @Documentry_Info VALUES(2,1,'Documentry')
INSERT INTO @Documentry_Info VALUES(3,2,'Film')
INSERT INTO @Documentry_Info VALUES(4,3,NULL)
DECLARE @Documentry_Info1 AS TABLE(TopicId INT,Topic VARCHAR(20),Preference INT,RowNo INT)
INSERT INTO @Documentry_Info1
SELECT *
FROM (
SELECT TopicId,Topic,Preference,ROW_NUMBER() OVER(PARTITION BY Topic ORDER BY (SELECT 0)) RowNo
FROM @Documentry_Info
WHERE Topic IS NOT NULL
) t
ORDER BY Preference ASC
SELECT TopicId,Topic
FROM @Documentry_Info1
WHERE RowNo = 1
Output
TopicId |
Topic |
5 |
ab |
1 |
Documentry |
3 |
Film |