select 
    CompanyID,WorkYear,WorkMonth,AccountCode,DeAment,BeAment,
    case Natrue when 'D' then DeAment+BeAment 
         when 'C' then DeAment-BeAment 
         else null
    end as Total,
    (select sum(case Natrue when 'D' then DeAment+BeAment 
         when 'C' then DeAment-BeAment 
         else null
    end)
    from 
        glvAccountSummary 
    where 
        CompanyID=a.CompanyID
    and  (
        WorkYear<a.WorkYear
    or   
        WorkYear=a.WorkYear
    and
        WorkMonth<=a.WorkMonth
      )
    ) as YTD_Total
from
   glvAccountSummary a

解决方案 »

  1.   

    朋友~1不正确~!~YTD_Total没有变化~1
      

  2.   

    --tryselect CompanyID,WorkYear,WorkMonth,AccountCode,DeAment,BeAment,
    Total=DeAment+BeAment*(case Natrue when 'D' then 1 when 'C' then -1 end) ,
    YTD_Total=(select sum(case Natrue when 'D' then DeAment+BeAment when 'C' then DeAment-BeAment end) 
    from glvAccountSummary where workyear<a.workyear  or (workyear=a.workyear and workmonth<=a.workmonth) )
    from glvAccountSummary a
      

  3.   

    select a.Workyear,a.Workmonth,sum(a.DeAment) as DeAment,sum(a.BeAment) as BeAment,
      sum(CASE nature WHEN 'D' THEN a.DeAmount+a.BeAmount
       WHEN 'C' THEN a.DeAment - a.BeAment else 0 END) AS Total,
      ( sum(CASE nature WHEN 'D' THEN a.DeAment+a.BeAment
       WHEN 'C' THEN a.DeAment - a.BeAment else 0 END)
      +isnull((select sum(CASE nature WHEN 'D' THEN DeAment+BeAment
       WHEN 'C' THEN DeAment - BeAment else 0 END)
       from glvAccountSummary 
       where Workyear*100+Workmonth<a.Workyear*100+a.Workmonth),0)) as YTDTotal
       from glvAccountSummary a 
      group by a.Workmonth,a.Workyear