Click here to Skip to main content
15,888,454 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Consider the below table

KEY    WO#    Parts   Name panels
77     11     1       aa     3
77     11     2       aa     4
81     12     2       bb     5
82     9      3       cc     6

Now i want to write a query for my report so that whenever theres a duplicate RKEY i want it to ignore it even though the number of parts in the duplicate RKEY are different and proceed with the next RKEY. Is this possible

End result
KEY    WO#    Parts   Name  panels
77     11     1       aa    3
81     12     2       bb    5
82     9      3       cc    6


What I have tried:

Not really sure how to achieve in sql2008
Posted
Updated 27-Jul-17 4:40am

Have you try Row_Number function? Here is an example using CTE and Row_Number functions.

SQL
DECLARE  @temp TABLE ([KEY] INT, WO INT, Parts INT, Name VARCHAR(10), Panels INT)

INSERT INTO @temp
SELECT 77, 11, 1, 'aa' , 3
UNION
SELECT 77, 11, 2, 'aa' , 4
UNION
SELECT 81, 12, 2, 'bb' , 5
UNION
SELECT 82, 9, 3, 'cc' ,6

SELECT * FROM @temp

;WITH temp AS (
SELECT ROW_NUMBER() OVER (PARTITION BY [Key]
                          ORDER BY [Key] DESC
                         ) AS myrownum
       ,*    
from @temp )
SELECT [Key], WO 'WO#', Parts, Name, Panels FROM temp WHERE myrownum = 1


Output:
Key	WO#	Parts	Name	Panels
77	11	   1	aa	     3
81	12	   2	bb	     5
82	 9	   3	cc	     6
 
Share this answer
 
Comments
Karthik_Mahalingam 27-Jul-17 23:28pm    
5
jaket-cp 31-Jul-17 11:49am    
why go half way with the cte example?
the select union could go into the cte right?
Try:
SQL
SELECT a.[Key], b.[WO#], b.Parts, b.Name, a.Panels FROM 
   (SELECT [Key], MIN(Panels) As Panels FROM MyTable GROUP BY [Key]) a
   JOIN MyTable b 
   ON a.[Key] = b.[Key] AND a.Panels = b.Panels
 
Share this answer
 

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