SQL汇总问题请教
表A:
地区 日期 订单号 销售数量
广东 2012-7-1 1111 2
广东 2012-7-2 1112 1
云南 2012-6-5 1001 1
...
表B:
订单号 退货数量
1111 1
1112 1
...
求:
地区 销售数量 退货数量 退货率
广东 3 2 66.67%
云南 1 0 0
...
谢谢!
[解决办法]
select a.地区,a.销售数量,b.退货数量,cast(b.退货数量*1.0/a.销售数量 as dec(18,2))+'%'from (select 地区,订单号,sum(销售数量) as 销售数量 from a group by 地区,退货数量)aleft join (select 订单号,sum(退货数量) as 退货数量 from b group by 退货数量)bon a.订单号=b.订单号
[解决办法]
declare @t table ( [地区] nvarchar(4), [日期] datetime, [订单号] varchar(8), [销售数量] int )insert into @tselect '广东','2012-7-1','1111',2 union allselect '广东','2012-7-2','1112',1 union allselect '云南','2012-6-5','1001',1declare @t2 table ([订单号] varchar(8) , [退货数量] int)insert into @t2select '1111',1union allselect '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 t3group by [地区](3 行受影响)(2 行受影响)地区 销售数量 退货数量 退货率---- ----------- ----------- ---------------------------------------广东 3 2 66.666666666666云南 1 NULL NULL警告: 聚合或其他 SET 操作消除了空值。(2 行受影响)
[解决办法]
--> 测试数据: #Aif object_id('tempdb.dbo.#A') is not null drop table #Acreate table #A ([地区] varchar(4),[日期] datetime,[订单号] int,[销售数量] int)insert into #Aselect '广东','2012-7-1',1111,2 union allselect '广东','2012-7-2',1112,1 union allselect '云南','2012-6-5',1001,1if object_id('tempdb.dbo.#B') is not null drop table #Bcreate table #B ([订单号] int,[退货数量] int)insert into #Bselect 1111,1 union allselect 1112,1;with temp as(select a.地区,SUM(b.退货数量) 退货数量,SUM(a.销售数量) 销售数量 from #A aleft 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*/