need to update Class value if Name occurs ONLY one time with Class value class1

Mohammad Ajmal Yazdani 391 Reputation points
2020-11-06T15:50:14.07+00:00

I have data like below,

create table #tbl (Name varchar(20), Class varchar(20))  
insert into #tbl values ('A', 'class1'), ('A', 'class2'), ('B', 'class1'), ('C', 'class2'), ('D', 'class3'), ('D', 'class1'), ('E', 'class4')  
select * from #tbl  
drop table #tbl  
  • A has 2 items
  • B has 1 item with class1
  • C has 1 item with class2
  • D has 2 items
  • E has one item with class4

I need to update class of "B" with value "XX" which has 1 items with class1, rest I need to ignore.

Expected output should be,

38044-image.png

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,626 questions
0 comments No comments
{count} votes

Accepted answer
  1. Tom Cooper 8,466 Reputation points
    2020-11-06T16:02:20.953+00:00
    ;With cte As
    (Select Name, Class, Count(*) Over(Partition By Name) As Cnt
    From #tbl)
    Update cte
    Set Class = 'XX'
    Where Class = 'class1' And Cnt = 1;
    

    Tom


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.