title: Oracle how to sum columns based on month number
body: <p>I have a summary table for months 1 - 12 based on fyr, fund, glkey, globject.  The problem I have is summing up the months up to a given month number for that row.  I can add a <code>Case</code> expression to add like </p>
  
  <pre><code>WHEN  2 then  m01 + m02 
  WHEN 12 then  m01 + m02 .. m12 
  </code></pre>
  
  <p>Does anyone know of a loop or better way of accomplishing this?</p>
  
  <p><img src="https://i.stack.imgur.com/Pkv0d.png" alt="Record in SQL"></p>
  
  <p>Function I created passing it 4 for month value should be 2537.50 but I get 15741.09.  </p>
  
  <pre><code>    CREATE OR REPLACE FUNCTION gla_sum_asof_month (
      fyr   IN NUMBER  , fund  IN NUMBER  , au    IN CHAR
    , acct  IN NUMBER  , sacct IN NUMBER  , mnth  IN NUMBER  )
    RETURN NUMBER
    IS
    rtn_amt NUMBER(18,2) := 0;
    amt NUMBER(18,2) := 0;
  BEGIN
  SELECT SUM(amt) INTO rtn_amt FROM (
    SELECT *
      FROM   app_reports.vw_glamounts 
    UNPIVOT
     (
       amt  FOR fmonth
       IN (m01 AS 1, m02 AS 2, m03 AS 3, m04 AS 4 , m05 AS 5 , m06 AS 6,
           m07 AS 7, m08 AS 8 , m09 AS 9, m10 AS 10, m11 AS 11, m12 AS 12)
      )
     ) a
      WHERE  a.Fiscal_Year            = fyr
            AND    a.company          = fund
            AND    a.acct_unit        = au
            AND    a.account          = acct
            AND   a. sub_account      = sacct
            AND   a.fmonth            &lt;= mnth;  -- filter # of months
  
     RETURN rtn_amt;
  END gla_sum_asof_month;
  </code></pre>