点击这里查看演示
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