Mysql calculation in select statement

Law picture Law · May 1, 2013 · Viewed 36.3k times · Source

I have been doing my office work in Excel.and my records have become too much and want to use mysql.i have a view from db it has the columns "date,stockdelivered,sales" i want to add another calculated field know as "stock balance". i know this is supposed to be done at the client side during data entry. i have a script that generates php list/report only based on views and tables,it has no option for adding calculation fields, so i would like to make a view in mysql if possible.

in excel i used to do it as follows.

enter image description here

i would like to know if this is possible in mysql.

enter image description here

i don't have much experience with my sql but i imagine first one must be able to select the previous row.colomn4 then add it to the current row.colomn2 minus current row.colomn3

If there is another way to achieve the same out put please suggest.

Answer

eggyal picture eggyal · May 1, 2013

Generally speaking, SQL wasn't really intended to yield "running totals" like you desire. Other RDBMS have introduced proprietary extensions to deliver analytic functions which enable calculations of this sort, but MySQL lacks such features.

Instead, one broadly has four options. In no particular order:

  1. Accumulate a running total in your application, as you loop over the resultset;

  2. Alter your schema to keep track of a running total within your database (especially good in situations like this, where new data is only ever appended "to the end");

  3. Group a self-join:

    SELECT   a.Sale_Date,
             SUM(a.Stock_Delivered)                AS Stock_Delivered,
             SUM(a.Units_Sold)                     AS Units_Sold,
             SUM(b.Stock_Delivered - b.Units_Sold) AS `Stock Balance`
    FROM     sales_report a
        JOIN sales_report b ON b.Sale_Date <= a.Sale_Date
    GROUP BY a.Sale_Date
    
  4. Accumulate the running total in a user variable:

    SELECT   Sale_Date,
             Stock_Delivered,
             Units_Sold,
             @t := @t + Stock_Delivered - Units_Sold AS `Stock Balance`
    FROM     sales_report, (SELECT @t:=0) init
    ORDER BY Sale_Date