27,579
社区成员
发帖
与我相关
我的任务
分享
--> 测试数据: [product]
if object_id('[product]') is not null drop table [product]
create table [product] (id int,pid int,code varchar(4),name varchar(1))
insert into [product]
select 1,0,null,'A' union all
select 2,1,'01','B' union all
select 3,1,'02','C' union all
select 4,2,'0101','D' union all
select 5,3,'0201','E' union all
select 6,1,'0001','F'
--> 测试数据: [sale]
if object_id('[sale]') is not null drop table [sale]
create table [sale] (id int,productId int,num int,price numeric(8,1))
insert into [sale]
select 1,4,2,5.5 union all
select 2,5,4,6.5 union all
select 3,6,1,20
;with wsp
as
(
select a.id,pid,name,num,totalprice=num*price from product a,sale b where a.id=b.productid
union all
select a.id,a.pid,a.name,num=b.num,totalprice=b.totalprice from product a,wsp b where a.id=b.pid
)
select name,totalNum=sum(num),totalPrice=sum(totalprice) from wsp group by name
/*结果:
name totalNum totalPrice
---- ----------- ---------------------------------------
A 7 57.0
B 2 11.0
C 4 26.0
D 2 11.0
E 4 26.0
F 1 20.0
*/