日期:2014-05-18  浏览次数:20556 次

请教高手这样的Sql 能写出吗 谢谢?
a                                 b

101-1                        
101-1-1                     1
101-1-2                     2
102-1                        
102-1-1                     3
102-1-2                     4
102-1-3                     5
.......

要结果如下
a                                 b

101-1                         3
101-1-1                     1
101-1-2                     2
102-1                         12
102-1-1                     3
102-1-2                     4
102-1-3                     5

就是把   101-1和102-1   的子的汇总
这样子能写吗?谢谢



------解决方案--------------------
declare @t table(a varchar(20),b int)
insert into @t select rtrim( '101-1 '),null
insert into @t select rtrim( '101-1-1 '),1
insert into @t select rtrim( '101-1-2 '),2
insert into @t select rtrim( '102-1 '),null
insert into @t select rtrim( '102-1-1 '),3
insert into @t select rtrim( '102-1-2 '),4
insert into @t select rtrim( '102-1-3 '),5

select
a.a,
isnull(a.b,(select sum(b) from @t where a like a.a+ '% ')) as b
from
@t a

/*
a b
-------------------- -----------
101-1 3
101-1-1 1
101-1-2 2
102-1 12
102-1-1 3
102-1-2 4
102-1-3 5
*/
------解决方案--------------------

declare @tab table
(
a varchar(10),
b int
)

insert into @tab select '101-1 ', null
insert into @tab select '101-1-1 ', 1
insert into @tab select '101-1-2 ', 2
insert into @tab select '102-1 ', null
insert into @tab select '102-1-1 ', 3
insert into @tab select '102-1-2 ', 4
insert into @tab select '102-1-3 ', 5

select a,case when b is null then (select sum(b) from @tab where charindex(tab.a,a) > 0 and a <> tab.a) else b end as b
from @tab tab

--结果
101-1 3
101-1-1 1
101-1-2 2
102-1 12
102-1-1 3
102-1-2 4
102-1-3 5

------解决方案--------------------
drop table tab
create table tab
(
a varchar(10),
b int
)

insert into tab select '101-1 ', null
insert