Jabda
Jabda

Reputation: 1792

sql server combine values in two tables

I am new to SQL in general and even newer to MS SQL. I apologize if the title isn't clear on what I want.

I have two tables an old one that I want to derive data from into a new table. The tables have the exact same columns but different number of rows. The new table has multiple copies of each value in the old table, which only has 2 occurences. see below comparison of two columns: letter and amount.

New table:

A  0 
A  0
A  0
B  0
B  0

old table:

A  12
A  0
B  10
B  0
C  23

What I want to achieve is adding the values of the amount column from the old table into just the first occurence of the leter in the new table like so:

A  12 
A  0
A  0
B  10
B  0

Inner join causes all the values to be filled ( so all the A's are set to 12).

Upvotes: 3

Views: 528

Answers (2)

user1499112
user1499112

Reputation:

click here to see Demo

declare @t table
(
    val varchar(2),
    digit int
)

insert into @t(val, digit)values('A', 0)
insert into @t(val, digit)values('A', 0)
insert into @t(val, digit)values('A', 0)
insert into @t(val, digit)values('B', 0)
insert into @t(val, digit)values('B', 0)

declare @t1 table
(
    val varchar(2),
    digit int
)

insert into @t1(val, digit)values('A', 12)
insert into @t1(val, digit)values('A', 0)
insert into @t1(val, digit)values('B', 10)
insert into @t1(val, digit)values('B', 0)
insert into @t1(val, digit)values('C', 23)


Select k.val, isNull(sum(k.digit + k1.digit), 0) as Digit from 
(
    Select ROW_NUMBER() over(partition by val order by val) as rowid, * from @t
)K
Left Join
(
    Select ROW_NUMBER() over(partition by val order by val) as rowid, * from @t1
)K1
on k.val = k1.val AND K.rowid = K1.rowid
group by k.val, K.rowid

Upvotes: 2

AnandPhadke
AnandPhadke

Reputation: 13486

try this:

DECLARE @test1 TABLE(col1 varchar(2),idn int)
insert into @test1
VALUES('A',0),
('A',0),
('A',0),
('B',0),
('B',0)

DECLARE @test2 TABLE(col1 varchar(2),idn int)
insert into @test2
VALUES('A',12),
('A',0),
('B',10),
('B',0),
('C',23)


;WITH CTE as (select *,ROW_NUMBER() over (partition by col1 order by col1) as rn from @test1)

update c SET c.idn=b.idn
from CTE c inner join (select col1,SUM(idn) as idn from @test2
group by col1) b
on c.col1 = b.col1 
where c.rn=1

select * from @test1

Upvotes: 2

Related Questions