积极答复者
SQL SELECT语句去重加计算

问题
-
新手疑惑我有个类似这样的表店铺 销售员 业绩 占店铺百分比 地区1 a 20 10% bj1 b 30 15% bj2 a 40 10% bj2 b 50 12.5% bj3 c 20 20% bj4 a 40 13.3% fj5 b 50 16.7% fj5 b 20 10% fj现在我要取出如下表销售员 业绩 占地区百分比 地区a 60 8.57%(60/700) bjb 100 14.28% bja 40 10% fjb 100 17.5% fj那个百分比怎么算,就是说要先算出地区总的,在算百分比。急求高手帮忙!!!!!!!!!!!!!!!我想写个存储过程!!!
- 已编辑 yazi308308 2009年11月26日 4:35
- 已移动 Sheng Jiang 蒋晟 2009年11月26日 16:10 SQL语法问题 (发件人:ADO.NET 与 LINQ)
答案
-
use Tempdb go --> --> declare @T table([店铺] int,[销售员] nvarchar(1),[业绩] int,[占店铺百分比] decimal(10,4),[地区] nvarchar(2)) Insert @T select 1,N'a',20,0.10,N'bj' union all select 1,N'b',30,0.15,N'bj' union all select 2,N'a',40,0.10,N'bj' union all select 2,N'b',50,0.125,N'bj' union all select 3,N'c',20,0.20,N'bj' union all select 4,N'a',40,0.133,N'fj' union all select 5,N'b',50,0.167,N'fj' union all select 5,N'b',20,0.10,N'fj' SELECT B.[地区],B.[销售员],sum(B.业绩) as 业绩,rtrim(cast(sum(B.业绩)/a.业绩*100 as numeric(18,2)))+'%' as 占地区百分比 from (select [地区],SUM(业绩) AS 业绩 FROM (Select [地区],[业绩]/[占店铺百分比] as 业绩 from @T t where [销售员]=(select top 1 [销售员] from @T where [地区]=t.[地区] and [店铺]=t.[店铺]))A group by [地区])A,@T B WHERE A.[地区]=B.[地区] GROUP BY B.[地区],B.[销售员],a.业绩 地区 销售员 业绩 占地区百分比 ---- ---- ----------- ------------------------------------------ bj a 60 8.57% bj b 80 11.43% bj c 20 2.86% fj a 40 5.00% fj b 70 8.75% (5 個資料列受到影響)
ROY WU(吳熹 )- 已标记为答案 Hong-Gang Chen - MSFTModerator 2009年11月30日 7:23
全部回复
-
这样计算:
select x.*, (x.业绩/y.地区业绩) as 占地区百分比 from
(select 销售员,sum(业绩) as 业绩,地区 from 业绩表 group by 销售员,地区) x
left join
(select sum(业绩) as 地区业绩,地区 from 业绩表 group by 地区) y
on x.地区=y.地区
******
注意要考虑地区业绩为0的时候 要报错
*************
你可以写个函数 考虑为0的直接赋0
或者是 用select case 如下:
case 地区业绩 when 0 then 0 end else (x.业绩/y.地区业绩) end -
use Tempdb go --> --> declare @T table([店铺] int,[销售员] nvarchar(1),[业绩] int,[占店铺百分比] decimal(10,4),[地区] nvarchar(2)) Insert @T select 1,N'a',20,0.10,N'bj' union all select 1,N'b',30,0.15,N'bj' union all select 2,N'a',40,0.10,N'bj' union all select 2,N'b',50,0.125,N'bj' union all select 3,N'c',20,0.20,N'bj' union all select 4,N'a',40,0.133,N'fj' union all select 5,N'b',50,0.167,N'fj' union all select 5,N'b',20,0.10,N'fj' SELECT B.[地区],B.[销售员],sum(B.业绩) as 业绩,rtrim(cast(sum(B.业绩)/a.业绩*100 as numeric(18,2)))+'%' as 占地区百分比 from (select [地区],SUM(业绩) AS 业绩 FROM (Select [地区],[业绩]/[占店铺百分比] as 业绩 from @T t where [销售员]=(select top 1 [销售员] from @T where [地区]=t.[地区] and [店铺]=t.[店铺]))A group by [地区])A,@T B WHERE A.[地区]=B.[地区] GROUP BY B.[地区],B.[销售员],a.业绩 地区 销售员 业绩 占地区百分比 ---- ---- ----------- ------------------------------------------ bj a 60 8.57% bj b 80 11.43% bj c 20 2.86% fj a 40 5.00% fj b 70 8.75% (5 個資料列受到影響)
ROY WU(吳熹 )- 已标记为答案 Hong-Gang Chen - MSFTModerator 2009年11月30日 7:23
-