Click here to Skip to main content
15,886,788 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi all,

I have a table in SQL where I want to retrieve all records inside. There are many columns inside the table like NAME, IDENTIFIER, TOTAL. Let's say this table has 6 records, if there is duplicate value under IDENTIFIER column, I want to retrieve the top 1 of those duplicate records + the other non-duplicate records.

For e.g.
**Table in SQL currently:**

----------------------------------------------------------------

NAME | IDENTIFIER | TOTAL

ab | 110011 | 10

cd | 110011 | 20

ef | 110012 | 30

gh | 110013 | 40

ij | 110014 | 50

kl | 110015 | 60

----------------------------------------------------------------
IDENTIFIER of 110011 is repeated but I want to retrieve one of those record.

**The output I want to achieve:**

----------------------------------------------------------------

NAME | IDENTIFIER | TOTAL

ab | 110011 | 10

ef | 110012 | 30

gh | 110013 | 40

ij | 110014 | 50

kl | 110015 | 60

----------------------------------------------------------------

Please help me on this, thanks!
Posted

If it is SQL Server, you can use RANK() to do your job.
Try something like-
SQL
SELECT [NAME],IDENTIFIER,TOTAL
FROM
(
	SELECT [NAME],IDENTIFIER,TOTAL,RANK() OVER (PARTITION BY IDENTIFIER ORDER BY TOTAL) AS SlNo
	FROM YourTable
) AS T
WHERE SlNo=1


EXAMPLE:
SQL
SELECT [NAME],IDENTIFIER,TOTAL
FROM
(
	SELECT [NAME],IDENTIFIER,TOTAL,RANK() OVER (PARTITION BY IDENTIFIER ORDER BY TOTAL) AS SlNo
	FROM
	(
		SELECT 'ab' [NAME], 110011 IDENTIFIER, 10 TOTAL
		UNION ALL
		SELECT 'cd', 110011, 20
		UNION ALL
		SELECT 'ef', 110012, 30
		UNION ALL
		SELECT 'gh', 110013, 40
		UNION ALL
		SELECT 'ij', 110014, 50
		UNION ALL
		SELECT 'kl', 110015, 60
	) AS T1
) AS T2
WHERE SlNo=1


Hope, it helps :)
 
Share this answer
 
v2
Comments
Maciej Los 6-Nov-15 14:22pm    
+5!
Suvendu Shekhar Giri 6-Nov-15 14:42pm    
Thank you @Maciej :)
You can check DISTINCT keyword.
 
Share this answer
 
Comments
Maciej Los 6-Nov-15 14:21pm    
Have you tried it? In this case, each record is differ from other, because of values in "Name" column.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900