在SQL Server中将第二个和连续的重复值提取为NULL [英] Fetching second and consecutive duplicate values as NULL in SQL server

查看:111
本文介绍了在SQL Server中将第二个和连续的重复值提取为NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的所有人,



我试图通过连接基于订单ID的两个表来获取第二个和连续的重复值为NULL,这两个表在两个表中都很常见。



我尝试过使用CTE和许多其他查询但没有得到准确的结果。



请检查在URL下方查看结果:



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



我需要相同数量的记录,但想要为OrderXML列的重复值返回NULL值(在屏幕中突出显示)在我的选择查询的最终输出中。



任何帮助或建议将不胜感激。



谢谢&问候,



我尝试过:



SQL中使用的CTE查询和UNION另外..我已经给出了我得到的结果的链接

解决方案

这是一个原理的演示,你必须适应它你自己的桌子

   -   一些示例数据 
创建 #demo(test VARCHAR (<跨度类= 代码位> 10 ),myvalue的<跨度类= 代码关键字> VARCHAR (<跨度类= 代码位> 10 ))
插入 进入 #demo(test,myValue) values
' val1'' value 1'),
' val1'' value 1'),
' val2'' value 1'),
' val2'' value 2 '),
' val2'' value 2'

查询:

;   cte  as  

select 测试,myvalue的,
ROW_NUMBER()<跨度类= 代码关键字> OVER (<跨度类= 代码关键字> PARTITION <跨度类=代码 - 关键字> BY test ORDER BY test,myValue) as rn
来自 #demo

选择 test, case rn = 1 然后 myValue else null end as myValue
来自 cte

评论:

由于ROW_NUMBER [ ^ ]我们得到 test 值中的每一行的行号。这就是你如何检测重复。



注意你如何选择订购价值,因为它将决定哪些被认为是重复的。


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

解决方案

Here is a demonstration of the principle, you'll have to adapt it to your own table

-- 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:

;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.


这篇关于在SQL Server中将第二个和连续的重复值提取为NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆