日期:2014-05-18 浏览次数:20673 次
select a.地区,a.销售数量,b.退货数量,cast(b.退货数量*1.0/a.销售数量 as dec(18,2))+'%' from (select 地区,订单号,sum(销售数量) as 销售数量 from a group by 地区,退货数量)a left join (select 订单号,sum(退货数量) as 退货数量 from b group by 退货数量)b on a.订单号=b.订单号
------解决方案--------------------
declare @t table
( [地区] nvarchar(4),
[日期] datetime,
[订单号] varchar(8),
[销售数量] int
)
insert into @t
select '广东','2012-7-1','1111',2 union all
select '广东','2012-7-2','1112',1 union all
select '云南','2012-6-5','1001',1
declare @t2 table
([订单号] varchar(8) ,
[退货数量] int
)
insert into @t2
select '1111',1union all
select '1112',1
;with t3 as
(
select [地区],[销售数量],[退货数量] from @t a left join @t2 b on a.[订单号] = b.[订单号]
)
select [地区],sum([销售数量]) as [销售数量],sum([退货数量]) as [退货数量],
sum([退货数量])*100.0/nullif(sum([销售数量]),0) as [退货率]
from t3
group by [地区]
(3 行受影响)
(2 行受影响)
地区 销售数量 退货数量 退货率
---- ----------- ----------- ---------------------------------------
广东 3 2 66.666666666666
云南 1 NULL NULL
警告: 聚合或其他 SET 操作消除了空值。
(2 行受影响)
------解决方案--------------------
--> 测试数据: #A
if object_id('tempdb.dbo.#A') is not null drop table #A
create table #A ([地区] varchar(4),[日期] datetime,[订单号] int,[销售数量] int)
insert into #A
select '广东','2012-7-1',1111,2 union all
select '广东','2012-7-2',1112,1 union all
select '云南','2012-6-5',1001,1
if object_id('tempdb.dbo.#B') is not null drop table #B
create table #B ([订单号] int,[退货数量] int)
insert into #B
select 1111,1 union all
select 1112,1
;with temp as(
select a.地区,SUM(b.退货数量) 退货数量,SUM(a.销售数量) 销售数量 from #A a
left join #B b on a.订单号=b.订单号
group by a.地区)
select 地区,
销售数量,
isnull(退货数量,0)退货数量,
isnull(cast(cast((退货数量+.0)/(销售数量+.0)*100 as decimal(12,2)) as varchar(10))+'%',0) 退货率
from temp
/*
地区 销售数量 退货数量 退货率
---- ----------- ----------- -----------
广东 3 2 66.67%
云南 1 0 0
*/