Try below
create table #temp
(
tranid int, company varchar(30),acct varchar(30)
)
GO
insert into #temp
select 1, 'A', 'ACT1' union all
select 1, 'A', 'ACT2' union all
select 1, 'B', 'ACT3' union all
select 2, 'A' , 'ACT1' union all
select 2 , 'C' , 'ACT1' union all
select 3 , 'A' , 'ACT5'
--finding only duplicates method 1
select * from
(select row_number() over(partition by company,acct order by tranid) rno, * from #temp) a
where rno> 1
--finding only duplicates method 2
select * from #temp a
where exists(select * from #temp b where a.company=b.company and a.acct=b.acct and a.tranid > b.tranid)
--select underlined record
select * from
(select row_number() over(partition by company,acct order by tranid) rno, * from #temp) a
where rno> 1
--underlined and bold record
WITH CTE1 as
(select row_number() over(partition by company,acct order by tranid) rno, * from #temp)
select a.tranid,a.company,a.acct,b.acct from CTE1 a inner join CTE1 b on a.company=b.company and a.acct=b.acct and b.rno=2
--select all other records other than bold and underlined.
--Method 1
WITH CTE1 as
(select row_number() over(partition by company,acct order by tranid) rno, * from #temp)
select a.tranid,a.company,a.acct from #temp a
except
select a.tranid,a.company,a.acct from CTE1 a inner join CTE1 b on a.company=b.company and a.acct=b.acct and b.rno=2
--method 2
;WITH CTE1 as
(select row_number() over(partition by company,acct order by tranid) rno, * from #temp)
select a.tranid,a.company,a.acct from CTE1 a left join CTE1 b on a.company=b.company and a.acct=b.acct and b.rno=2
where b.acct is null
Thanks
Saravana Kumar C
No comments:
Post a Comment