--测试数据 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.名称 godrop table 商品表,销售表/*--测试结果编码 名称 数量 金额 ------------------ ---------- ----------- ----------- 合计 AB 5 270.0000 001-002-001 ABC 3 150.0000 001-002-002 ABCd 2 120.0000 合计 BA 3 180.0000 002-002-001 BAC 3 180.0000(所影响的行数为 5 行)--*/ 用这种方法,输出的格式有时不稳定,可能没有设置主键。
在没有用ORDER BY 语句输出,数据库的变动性太大了。
--排序的问题: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
--只统计到指定级别的问题:select c.编码,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
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.名称
godrop table 商品表,销售表/*--测试结果编码 名称 数量 金额
------------------ ---------- ----------- -----------
合计 AB 5 270.0000
001-002-001 ABC 3 150.0000
001-002-002 ABCd 2 120.0000
合计 BA 3 180.0000
002-002-001 BAC 3 180.0000(所影响的行数为 5 行)--*/
用这种方法,输出的格式有时不稳定,可能没有设置主键。
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
,数量=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