Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Dear All,

I am trying to fetch second and consecutive duplicate values as NULL by joining two tables based on Order ID which is common in both the tables.

I have tried using CTE and many other queries but not getting accurate result.

Please check the below URL to see the result :

http://www.ikatraining.com/sqlquery.png

I need same number of records but want to return NULL value for the duplicate values for OrderXML column (highlighted in the screen shot) in the final output of my select query.

Any help or suggestion would be greatly appreciated.

Thanks & Regards,

What I have tried:

CTE used in SQL Query and UNION Also.. I have given the link for the result I am getting
Posted
Updated 13-Aug-18 1:37am
Comments
CHill60 13-Aug-18 7:08am    
Please do not include links to images to explain your problem. You could have easily typed that information into your question and your link makes your post look like spam.
You say you have tried using a CTE and a UNION - then show the code that you have tried

1 solution

Here is a demonstration of the principle, you'll have to adapt it to your own table
SQL
-- Some sample data
create table #demo (test varchar(10), myValue varchar(10))
insert into #demo (test, myValue) values
('val1', 'value 1'),
('val1', 'value 1'),
('val2', 'value 1'),
('val2', 'value 2'),
('val2', 'value 2')
The query:
SQL
;with cte as 
(
	select test, myValue, 
		row_number() OVER (PARTITION BY test ORDER BY test, myValue) as rn
	from #demo
)
select test, case when rn = 1 then myValue else null end as myValue
from cte
Comment:
Because of the partition on ROW_NUMBER [^] we are getting a row number for each row within a test value. That is how you can detect the "duplicates".

Take care on how you choose to order the values as it will determine which are deemed to be duplicates.
 
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