您的位置:首页 > 数据库

按产品分类进行销售统计的sql

2010-05-16 11:09 351 查看
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
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息