select 编码,名称,数量
from(
select 编码=case max(c.级别) when 2 then '合计' else c.编码 end
,c.名称
,数量=sum(b.数量),金额=sum(b.金额)
,s=c.编码
from 商品表 a
join 销售表 b on a.id=b.id
join 商品表 c on a.编码 like c.编码+'%' and c.级别>=2
group by c.编码,c.名称
)a order by s
--测试数据
create table 商品表(
ID Int,
编码 NVarchar(60),
名称 NVarchar(250),
父亲ID Int ,
级别 Int,
是否节点 Int
)
create table 销售表(
Id Int,
数量 Int,
单价 Decimal(18,4) Null,
金额 Decimal(18,4) Null)
insert into 商品表
select 1,'001','A',0,1,0
union all select 2,'001-002','AB',1,2,0
union all select 3,'001-002-001','ABC',2,3,1
union all select 4,'002','B',0,1,0
union all select 5,'002-002','BA',4,2,0
union all select 6,'002-002-001','BAC',5,3,1
union all select 7,'001-002-002','ABCd',2,3,1
Insert into 销售表
select 3,1,50,50
union all select 3,2,50,100
union all select 6,1,60,60
union all select 6,2,60,120
union all select 7,2,60,120
go
--查询
select 编码=case max(c.级别) when 2 then '合计' else c.编码 end
,c.名称
,数量=sum(b.数量),金额=sum(b.金额)
from 商品表 a
join 销售表 b on a.id=b.id
join 商品表 c on a.编码 like c.编码+'%' and c.级别>=2
group by c.编码,c.名称
go