SQL - cumulative sum in postgres












0















I have my data like this:



item - initial_value - amount - dateofpurchase 
A 100 -3 2018-11-22
A 100 -2 2018-11-22
B 200 -5 2018-11-22
B 200 6 2018-11-22
B 200 -1 2018-11-22


(everything is ordered by date and time)



I want to calculate this column, that shows how much stock do you have after each step and taking in count the last amount



item - initial_value - amount - dateofpurchase - cumulative
A 100 -3 2018-11-22 97
A 100 -2 2018-11-22 95
B 200 -5 2018-11-22 195
B 200 6 2018-11-22 201
B 200 -1 2018-11-22 200


I've been trying a sum function with unbounded preceding and current row with no luck










share|improve this question



























    0















    I have my data like this:



    item - initial_value - amount - dateofpurchase 
    A 100 -3 2018-11-22
    A 100 -2 2018-11-22
    B 200 -5 2018-11-22
    B 200 6 2018-11-22
    B 200 -1 2018-11-22


    (everything is ordered by date and time)



    I want to calculate this column, that shows how much stock do you have after each step and taking in count the last amount



    item - initial_value - amount - dateofpurchase - cumulative
    A 100 -3 2018-11-22 97
    A 100 -2 2018-11-22 95
    B 200 -5 2018-11-22 195
    B 200 6 2018-11-22 201
    B 200 -1 2018-11-22 200


    I've been trying a sum function with unbounded preceding and current row with no luck










    share|improve this question

























      0












      0








      0


      2






      I have my data like this:



      item - initial_value - amount - dateofpurchase 
      A 100 -3 2018-11-22
      A 100 -2 2018-11-22
      B 200 -5 2018-11-22
      B 200 6 2018-11-22
      B 200 -1 2018-11-22


      (everything is ordered by date and time)



      I want to calculate this column, that shows how much stock do you have after each step and taking in count the last amount



      item - initial_value - amount - dateofpurchase - cumulative
      A 100 -3 2018-11-22 97
      A 100 -2 2018-11-22 95
      B 200 -5 2018-11-22 195
      B 200 6 2018-11-22 201
      B 200 -1 2018-11-22 200


      I've been trying a sum function with unbounded preceding and current row with no luck










      share|improve this question














      I have my data like this:



      item - initial_value - amount - dateofpurchase 
      A 100 -3 2018-11-22
      A 100 -2 2018-11-22
      B 200 -5 2018-11-22
      B 200 6 2018-11-22
      B 200 -1 2018-11-22


      (everything is ordered by date and time)



      I want to calculate this column, that shows how much stock do you have after each step and taking in count the last amount



      item - initial_value - amount - dateofpurchase - cumulative
      A 100 -3 2018-11-22 97
      A 100 -2 2018-11-22 95
      B 200 -5 2018-11-22 195
      B 200 6 2018-11-22 201
      B 200 -1 2018-11-22 200


      I've been trying a sum function with unbounded preceding and current row with no luck







      sql postgresql






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 23 '18 at 12:49









      Naty BizzNaty Bizz

      80951841




      80951841
























          2 Answers
          2






          active

          oldest

          votes


















          1














          You can use window functions and subtraction:



          select t.*,
          ( initial_amount +
          sum(amount) over (partition by item order by date_of_purchase)
          ) as cumulative
          from t;





          share|improve this answer































            0














            use window function



            with cte as
            (
            select 'A' item, 100 as initial_value, -3 amount, '2018-11-22'::date as dateofpurchase
            union all
            select 'A' ,100, -2, '2018-11-22'
            union all
            select 'B',200, -5,'2018-11-22'
            union all
            select 'B',200, 6,'2018-11-22'
            union all
            select 'B',200, -1,'2018-11-22'
            )
            , t1 as
            (select t.*, row_number() over(partition by item order by dateofpurchase) rn

            from cte t
            )
            , t3 as
            (select *, case when rn=1 then initial_value else 0 end as val from t1
            ) select item,initial_value,amount,dateofpurchase, sum(val+amount) over(partition by item order by rn) as cumulative from t3


            Sample output



            item    initial_value   amount  dateofpurchase  cumulative
            A 100 -3 2018-11-22 97
            A 100 -2 2018-11-22 95
            B 200 -5 2018-11-22 195
            B 200 6 2018-11-22 201
            B 200 -1 2018-11-22 200


            demo link






            share|improve this answer

























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447037%2fsql-cumulative-sum-in-postgres%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              1














              You can use window functions and subtraction:



              select t.*,
              ( initial_amount +
              sum(amount) over (partition by item order by date_of_purchase)
              ) as cumulative
              from t;





              share|improve this answer




























                1














                You can use window functions and subtraction:



                select t.*,
                ( initial_amount +
                sum(amount) over (partition by item order by date_of_purchase)
                ) as cumulative
                from t;





                share|improve this answer


























                  1












                  1








                  1







                  You can use window functions and subtraction:



                  select t.*,
                  ( initial_amount +
                  sum(amount) over (partition by item order by date_of_purchase)
                  ) as cumulative
                  from t;





                  share|improve this answer













                  You can use window functions and subtraction:



                  select t.*,
                  ( initial_amount +
                  sum(amount) over (partition by item order by date_of_purchase)
                  ) as cumulative
                  from t;






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 23 '18 at 12:51









                  Gordon LinoffGordon Linoff

                  771k35304404




                  771k35304404

























                      0














                      use window function



                      with cte as
                      (
                      select 'A' item, 100 as initial_value, -3 amount, '2018-11-22'::date as dateofpurchase
                      union all
                      select 'A' ,100, -2, '2018-11-22'
                      union all
                      select 'B',200, -5,'2018-11-22'
                      union all
                      select 'B',200, 6,'2018-11-22'
                      union all
                      select 'B',200, -1,'2018-11-22'
                      )
                      , t1 as
                      (select t.*, row_number() over(partition by item order by dateofpurchase) rn

                      from cte t
                      )
                      , t3 as
                      (select *, case when rn=1 then initial_value else 0 end as val from t1
                      ) select item,initial_value,amount,dateofpurchase, sum(val+amount) over(partition by item order by rn) as cumulative from t3


                      Sample output



                      item    initial_value   amount  dateofpurchase  cumulative
                      A 100 -3 2018-11-22 97
                      A 100 -2 2018-11-22 95
                      B 200 -5 2018-11-22 195
                      B 200 6 2018-11-22 201
                      B 200 -1 2018-11-22 200


                      demo link






                      share|improve this answer






























                        0














                        use window function



                        with cte as
                        (
                        select 'A' item, 100 as initial_value, -3 amount, '2018-11-22'::date as dateofpurchase
                        union all
                        select 'A' ,100, -2, '2018-11-22'
                        union all
                        select 'B',200, -5,'2018-11-22'
                        union all
                        select 'B',200, 6,'2018-11-22'
                        union all
                        select 'B',200, -1,'2018-11-22'
                        )
                        , t1 as
                        (select t.*, row_number() over(partition by item order by dateofpurchase) rn

                        from cte t
                        )
                        , t3 as
                        (select *, case when rn=1 then initial_value else 0 end as val from t1
                        ) select item,initial_value,amount,dateofpurchase, sum(val+amount) over(partition by item order by rn) as cumulative from t3


                        Sample output



                        item    initial_value   amount  dateofpurchase  cumulative
                        A 100 -3 2018-11-22 97
                        A 100 -2 2018-11-22 95
                        B 200 -5 2018-11-22 195
                        B 200 6 2018-11-22 201
                        B 200 -1 2018-11-22 200


                        demo link






                        share|improve this answer




























                          0












                          0








                          0







                          use window function



                          with cte as
                          (
                          select 'A' item, 100 as initial_value, -3 amount, '2018-11-22'::date as dateofpurchase
                          union all
                          select 'A' ,100, -2, '2018-11-22'
                          union all
                          select 'B',200, -5,'2018-11-22'
                          union all
                          select 'B',200, 6,'2018-11-22'
                          union all
                          select 'B',200, -1,'2018-11-22'
                          )
                          , t1 as
                          (select t.*, row_number() over(partition by item order by dateofpurchase) rn

                          from cte t
                          )
                          , t3 as
                          (select *, case when rn=1 then initial_value else 0 end as val from t1
                          ) select item,initial_value,amount,dateofpurchase, sum(val+amount) over(partition by item order by rn) as cumulative from t3


                          Sample output



                          item    initial_value   amount  dateofpurchase  cumulative
                          A 100 -3 2018-11-22 97
                          A 100 -2 2018-11-22 95
                          B 200 -5 2018-11-22 195
                          B 200 6 2018-11-22 201
                          B 200 -1 2018-11-22 200


                          demo link






                          share|improve this answer















                          use window function



                          with cte as
                          (
                          select 'A' item, 100 as initial_value, -3 amount, '2018-11-22'::date as dateofpurchase
                          union all
                          select 'A' ,100, -2, '2018-11-22'
                          union all
                          select 'B',200, -5,'2018-11-22'
                          union all
                          select 'B',200, 6,'2018-11-22'
                          union all
                          select 'B',200, -1,'2018-11-22'
                          )
                          , t1 as
                          (select t.*, row_number() over(partition by item order by dateofpurchase) rn

                          from cte t
                          )
                          , t3 as
                          (select *, case when rn=1 then initial_value else 0 end as val from t1
                          ) select item,initial_value,amount,dateofpurchase, sum(val+amount) over(partition by item order by rn) as cumulative from t3


                          Sample output



                          item    initial_value   amount  dateofpurchase  cumulative
                          A 100 -3 2018-11-22 97
                          A 100 -2 2018-11-22 95
                          B 200 -5 2018-11-22 195
                          B 200 6 2018-11-22 201
                          B 200 -1 2018-11-22 200


                          demo link







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 23 '18 at 13:15

























                          answered Nov 23 '18 at 12:51









                          Zaynul Abadin TuhinZaynul Abadin Tuhin

                          12.9k2932




                          12.9k2932






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53447037%2fsql-cumulative-sum-in-postgres%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              404 Error Contact Form 7 ajax form submitting

                              How to know if a Active Directory user can login interactively

                              TypeError: fit_transform() missing 1 required positional argument: 'X'