日期:2014-05-17 浏览次数:20739 次
--测试环境 if object_id('[tb]') is not null drop table [tb] go create table [tb]([客户] varchar(1),[单据类型] varchar(4),[余额] numeric(10,1),[单据日期] datetime,账龄 int) insert [tb] select 'A','应收','1292301','2010-1-31 00:00','121' union all select 'A','应收','1139292','2010-2-28 00:00','93' union all select 'A','应收','1152316.8','2010-3-23 00:00','70' union all select 'A','应收','78148.8','2010-3-23 00:00','70' union all select 'A','应收','1230465.6','2010-4-28 00:00','34' union all select 'A','应收','1204416','2010-5-25 00:00','7' union all select 'A','收款','-1204416','2010-2-28 00:00','93' union all select 'A','收款','-1139292','2010-3-31 00:00','62' union all select 'A','收款','-1230465.6','2010-4-30 00:00','32' union all select 'A','收款','-1230465.6','2010-5-31 00:00','1' union all select 'B','应收','196668','2010-1-31 00:00','121' union all select 'B','应收','8866','2010-2-25 00:00','96' union all select 'B','应收','154677.6','2010-2-28 00:00','93' union all select 'B','应收','508741.2','2010-3-23 00:00','70' union all select 'B','应收','453157.2','2010-4-28 00:00','34' union all select 'B','应收','411469.2','2010-5-25 00:00','7' union all select 'B','收款','-196668','2010-3-31 00:00','62' union all select 'B','收款','-154677.6','2010-4-30 00:00','32' union all select 'B','收款','-8866','2010-4-30 00:00','32' union all select 'B','收款','-508741.2','2010-5-31 00:00','1' union all select 'C','应收','506268','2010-1-21 00:00','131' union all select 'C','应收','536491.2','2010-2-25 00:00','96' union all select 'C','应收','633080','2010-3-23 00:00','70' union all select 'C','应收','426927.2','2010-4-19 00:00','43' union all select 'C','应收','913399.2','2010-5-17 00:00','15' union all select 'C','应收','959968.8','2009-12-30 00:00','153' union all select 'C','应收','584511.2','2009-9-30 00:00','244' union all select 'C','应收','974943.2','2009-4-30 00:00','397' union all select 'C','应收','45332.82','2009-1-23 00:00','494' go select 客户, sum(余额)as 应收余额, 0 as 账期内本币金额, case when sum(case when 单据类型='应收'and 账龄 > 30 then 余额 else 0 end)+ sum(case when 单据类型='收款' then 余额 else 0 end)>=0 then sum(case when 单据类型='应收'and 账龄 between 1 and 31 then 余额 else 0 end) else case when sum(case when 单据类型='应收'and 账龄 > 31 then 余额 else 0 end)+