日期:2014-05-17  浏览次数:20457 次

关于去掉重复数据的问题,求高手解答
我有三张表A,B,C
A的字段有Name(委托方)varchar(50),Money(管理费)decimal,Deparment(分配部门)varchar(50),Create(创建时间datetime,CostName费用名称(水费,电费等)

B的字段有Close(结算状态1为结算0为未结算)varchar(1),CostType(费用类型0收费1付费)varchar(1),ShouldMoney(金额)decimal(18,4),Num(业务号)varchar(50),Currency_Rate(汇率,汇率不是统一的,有美元,日元等)decimal(18,4)

C的字段有Num(业务号)varchar(50),Name(委托方)varchar(50),Deparment(分配部门)varchar(50),InputDate(录入时间)datetime,
我想根据条件求出存利润,条件就是A表的分配部门和创建时间,和C表的委托方,
A的委托方与C的委托方是关联的B的业务号和C的业务号是关联的

我想求出2013-5月份所有的存利润(包括已结算和未结算的),公式是
(已结算的收费*汇率-已结算的付费*汇率)=已结算毛利润
(未结算的收费*汇率-未结算的付费*汇率)=为结算毛利润

(已结算毛利润+未结算毛利润)-管理费 = 纯利润

我想最终显示的格式是这样的

委托方  分配部门   票数(已结算和未结算票数的总和) 应收费用   应付费用   管理费用   纯利润

但是查到的数据有一些事重复的
这是我写的查询语句求高手分析一下

select bbd.Operate_Name as '经营单位',cmf.AllotDepartment as '分配部门',cmf.CostName as '费用名称'
--,(count(case when CostType='0' and Flag_ClosingCost='1' then bbd.Consignor else 0 end))
,sum(case when CostType='0' and Flag_ClosingCost='1' then ShouldMoney else 0 end)*(Currency_Rate) as '应收金额'
,sum(case when CostType='1' and Flag_ClosingCost='1' then ShouldMoney else 0 end)*(Currency_Rate)  as '应付金额'
,sum(case when CostType='0' and Flag_ClosingCost='1' then ShouldMoney else 0 end)*(Currency_Rate) -sum(case when CostType='1' and Flag_ClosingCost='1' then ShouldMoney else 0 end)*(Currency_Rate)  as '毛利润'
,sum([Money]) as '管理费用'
,((sum(case when CostType='0' and Flag_ClosingCost='1' then ShouldMoney else 0 end)*(Currency_Rate) -sum(case when CostType='1' and Flag_ClosingCost='1' then ShouldMoney else 0 end)*(Currency_Rate) )-sum([Money])) as '纯利润'
from [cost_FeeInfo] as cfi,bus_BusinessDetail as bbd,cost_ManageFee as cmf 
where cfi.BusinessNum=bbd.BusinessNum and cmf.Consignor = bbd.Operate_Name and bbd.IsAvailable='True'
  and Flag_ClosingCost='1'
 AND bbd.InputDate BETWEEN '2013-05-01 00:00:00' AND '2013-05-31 00:00:00' 
AND cmf.CreateDate BETWEEN '2013-05-01 00:00:00' AND '2013-05-31 00:00:00' 
GROUP BY bbd.Operate_Name,cmf.AllotDepartment,[Money],Currency_Rate,cmf.CostName

出现以下结果
是重复因为图片不能上传,所以不能发截图,求高手给看看原因,急急急谢啦

------解决方案--------------------
语句上没有看出问题来,但是写的的确是够乱的了
估计是你在内联的时候,有重复数据了,个人建议可以这样看
先用inner join 吧数据都链接好,然后在外面写
select  sum(case***) as xxx from (select * from a,b,c where xxx) t 
group by xxxx


------解决方案--------------------
一般多表联合查询有重复数据产生,是因为满足表关联条件的数有重复
呈现1对多或者多对多的关系,若要去重,可以先将有重复数据的表单表分组合并后再进行关联