3

一般来说,我是 SQL 新手,甚至对 MS SQL 也是新手。如果标题不清楚我想要什么,我深表歉意。

我有两个表,一个旧表,我想从中获取数据到一个新表中。这些表具有完全相同的列,但行数不同。新表对旧表中的每个值都有多个副本,旧表仅出现 2 次。请参阅下面两列的比较:字母和金额。

新表:

A  0 
A  0
A  0
B  0
B  0

旧表:

A  12
A  0
B  10
B  0
C  23

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

A  12 
A  0
A  0
B  10
B  0

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

4

2 回答 2

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
于 2012-08-07T16:40:55.320 回答
2

点击这里查看演示

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
于 2012-08-07T16:48:14.143 回答