简体   繁体   中英

Update duplicates records with different values in SQL Server

I have 2 temporary tables

tempA:

attr1   | attr2   |  attr3    |   expense
 ab         bc       8967         4567
 ab         bc       4543         922.65
 ab         bc       3476         7878.2

tempB

attr4   | attr5   |  attr6    |   revenue
ab          bc        8967         25.1
ab          bc        4543         25.2
ab          bc        3476         25.3
ab          bc        8967         25.4
ab          bc        3476         25.5

I have a third temp table, #tempC this table is built based on #tempA and #tempB tables.

The issue that I am facing is that #tempC is storing these:

attr1  |  attr5  |   revenue  |  expense
ab         bc         25.1        4567
ab         bc         25.2        922.65
ab         bc         25.3        7878.2
ab         bc         25.4        4567
ab         bc         25.5        7878.2

it assigns expense everytime there is match between attr3 and attr6(it should do it when the match is for the first time)

so I need this for #tempC

attr1  |  attr5  |   revenue  |  expense
ab           bc       25.1        4567
ab           bc       25.2        922.65
ab           bc       25.3        7878.2
ab           bc       25.4        0
ab           bc       25.5        0

in this case if there is a match again between attr3 and attr6 it should store 0.

How could I solve that.

(attr3 and attr6 are varchar and they are not pk, or fk they are just simple attributes)

you can use below query for required output.With the help of window function we can achieve it easily.

create table #tempA (attr1 VARCHAR(10), attr2 VARCHAR(10), attr3 VARCHAR(10), expense NUMERIC(18,2))

create table #tempB (attr4 VARCHAR(10), attr5 VARCHAR(10), attr6 VARCHAR(10), revenue NUMERIC(18,2))

INSERT INTO #tempA
VALUES('ab', 'bc', '8967', 4567),
      ('ab', 'bc', '4543', 922.65),
      ('ab', 'bc', '3476', 7878.2)   

INSERT INTO #tempB
VALUES('ab', 'bc', '8967', 25.1),
      ('ab', 'bc', '4543', 25.2),
      ('ab', 'bc', '3476', 25.3),
      ('ab', 'bc', '8967', 25.4),
      ('ab', 'bc', '3476', 25.5)


 select distinct attr1,
   attr5,
   revenue,
   case when b.rn = 1 then expense else 0 end as expense 
 from #tempA a
 join (select *,ROW_NUMBER()over(partition by attr6 order by attr4,attr5,attr6) as rn from #tempB ) b 
    on b.attr4 = a.attr1 
      and b.attr5 = a.attr2 
      and b.attr6 = a.attr3  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM