表table1如下:
id score
1 null
2 null
11 null
12 null
13 null
21 null
1101 100
1102 200
1201 150
1202 200
1203 null
1301 null
2101 500
结果要求:
id score
1 650
2 500
11 300
12 350
13 0
21 500
1101 100
1102 200
1201 150
1202 200
1203 null
1301 null
2101 500
说明:一级的id长度为1,二级的id长度为2,三级的id长度为4。
table1的中只有三级id的score不为空。
要求:一级为对应三级(二级)的和
二级为对应三级的和
id score
1 null
2 null
11 null
12 null
13 null
21 null
1101 100
1102 200
1201 150
1202 200
1203 null
1301 null
2101 500
结果要求:
id score
1 650
2 500
11 300
12 350
13 0
21 500
1101 100
1102 200
1201 150
1202 200
1203 null
1301 null
2101 500
说明:一级的id长度为1,二级的id长度为2,三级的id长度为4。
table1的中只有三级id的score不为空。
要求:一级为对应三级(二级)的和
二级为对应三级的和
Insert @T
select 1,null union all
select 2,null union all
select 11,null union all
select 12,null union all
select 13,null union all
select 21,null union all
select 1101,100 union all
select 1102,200 union all
select 1201,150 union all
select 1202,200 union all
select 1203,null union all
select 1301,null union all
select 2101,500
Select [id],[score]=(select sum(isnull([score],0)) from @T where [id] like rtrim(t.[id])+'%')
from @T t
order by
[id] asc(13 個資料列受到影響)
id score
----------- -----------
1 650
2 500
11 300
12 350
13 0
21 500
1101 100
1102 200
1201 150
1202 200
1203 0
1301 0
2101 500(13 個資料列受到影響)
union all
select left(cast(id as varchar),2) id, sum(score) score from table1 where len(cast(id as varchar)) = 4 group by left(cast(id as varchar),2)
union all
select * from table1 where len(cast(id as varchar)) = 4