SQL Server将两个表中的值组合在一起

时间:2012-08-07 16:23:28

标签: sql-server sql-server-2008 sql-server-2005

我是SQL的新手,甚至是MS SQL的新手。如果标题不清楚我想要什么,我道歉。

我有两张表,我想将数据从新表中导出。这些表具有完全相同的列但行数不同。新表在旧表中具有每个值的多个副本,其中仅有2个出现。见下面两列的比较:字母和金额。

新表:

A  0 
A  0
A  0
B  0
B  0
老桌子:

A  12
A  0
B  10
B  0
C  23

我想要实现的是将旧表中的amount列的值添加到新表中第一次出现的leter中,如下所示:

A  12 
A  0
A  0
B  10
B  0

内部联接会导致填充所有值(因此所有A都设置为12)。

2 个答案:

答案 0 :(得分:2)

试试这个:

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

答案 1 :(得分:2)

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