Mysql calculation in select statement

…衆ロ難τιáo~ 提交于 2019-12-05 16:43:37

Eggyal has four good solutions. I think the cleanest way to do a running total in MySQL is using a correlated subquery -- it eliminates the group by at the end. So I would add to the list of options:

SELECT sr.Sale_Date, sr.Stock_Delivered, sr.Units_Sold,
       (select SUM(sr2.Stock_Delivered) - sum(sr2.Units_Sold)
        from sales_report sr2
        where sr2.sale_date <= sr.sale_date
       ) as StockBalance
FROM  sales_report sr
ORDER BY Sale_Date

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
    
SELECT
  sales_report.Stock_Delivered,
  sales_report.Units_Sold,
  sales_report.Stock_Delivered - sales_report.Units_Sold
FROM
  sales_report;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!