日期:2014-05-18 浏览次数:20559 次
create table 销量表
(产品编号 int, 用户 int, 区间 varchar(6),
数量 int, 品牌 varchar(5), 包装类型 varchar(5))
insert into 销量表
select 100001, 3000, '201203', 11.00, 'Bud', 'BBT' union all
select 100002, 3000, '201203', 11.00, 'Bud', 'SBT' union all
select 100002, 3000, '201203', 11.00, 'Bud', 'SBT' union all
select 100003, 3000, '201203', 11.00, 'Bud', 'CAN' union all
select 100004, 3000, '201203', 11.00, 'Bud', 'OTH' union all
select 100005, 3000, '201203', 11.00, 'Htb', 'OTH'
select * into #t
from
(select 品牌,'' 包装类型,sum(数量) '数量'
from 销量表 group by 品牌
union all
select 品牌,包装类型,sum(数量) '数量'
from 销量表 group by 品牌,包装类型
) t order by t.品牌
select 'Total' 品牌,'' 包装类型,sum(数量) 数量 from 销量表
union all
select '',包装类型,sum(数量) from 销量表 group by 包装类型
union all
select * from #t
品牌 包装类型 数量
----- ----- -----------
Total 66
BBT 11
CAN 11
OTH 22
SBT 22
Bud 55
Bud BBT 11
Bud CAN 11
Bud OTH 11
Bud SBT 22
Htb 11
Htb OTH 11
(12 row(s) affected)
------解决方案--------------------
create table 销量表
(产品编号 int, 用户 int, 区间 varchar(6),
数量 int, 品牌 varchar(5), 包装类型 varchar(5))
insert into 销量表
select 100001, 3000, '201203', 11.00, 'Bud', 'BBT' union all
select 100002, 3000, '201203', 11.00, 'Bud', 'SBT' union all
select 100002, 3000, '201203', 11.00, 'Bud', 'SBT' union all
select 100003, 3000, '201203', 11.00, 'Bud', 'CAN' union all
select 100004, 3000, '201203', 11.00, 'Bud', 'OTH' union all
select 100005, 3000, '201203', 11.00, 'Htb', 'OTH'
select case when t.包装类型='' then t.品牌 else '' end '品牌',
t.包装类型,t.数量 into #t from
(select 品牌,'' 包装类型,sum(数量) '数量'
from 销量表 group by 品牌
union all
select 品牌,包装类型,sum(数量) '数量'
from 销量表 group by 品牌,包装类型
) t order by t.品牌
select 'Total' 品牌,'' 包装类型,sum(数量) 数量 from 销量表
union all
select '',包装类型,sum(数量) from 销量表 group by 包装类型
union all
select * from #t
品牌 包装类型 数量
----- ----- -----------
Total 66
BBT 11
CAN 11
OTH 22
SBT 22
Bud 55
BBT 11
CAN 11
OTH 11
SBT 22
Htb 11
OTH 11
(12 row(s) affected)
------解决方案--------------------
create table tb(产品编号 varchar(10),用户 varchar(10),区间 varchar(10),数量 decimal(18,2) ,品牌 varchar(10),包装类型 varchar(10))
insert into tb values('100001', '3000', '201203', 11.00 ,'Bud', 'BBT')
insert into tb values('100002', '3000', '201203', 11.00 ,'Bud', 'SBT')
insert into tb values('100002', '3000', '201203', 11.00 ,'Bud', 'SBT')
insert into tb values('100003', '3000', '201203', 11.00 ,'Bud', 'CAN')
insert into tb values('100004', '3000', '201203', 11.00 ,'Bud', 'OTH')
insert into tb values('100005', '3000', '201203', 11.00 ,'Htb', 'OTH')
go
--select 'Total' c1, 'total' c2 , sum(数量) c3 from tb
select * from
(
select 'Total' c1,包装类型 c2, sum(数量) c3 from tb group by 包装类型
union all
select isnull(品牌,'Total') c1, isnull(包装类型,'合计') c2 , sum(数量) c3 from tb group by 品牌 , 包装类型 with rollup
) t
order by case when c1 = 'total' then 1 else 2 end , c1 , (case when c2 = '合计' then 1 else 2 end)
drop table tb/*
c1 c2