1

I am creating one SQL query for stock entry. In the last column, I need the total of the previous stock purchase.

S No    Product Code    Qty     Qty Total
1       PO1             5       5  
2       PO1             12      17
3       PO1             10      27
4       PO1              8      35
5       PO1              9      44
6       PO1             16      60

In every row of the last column, I am adding all the previous quantity for example S no. 1 quantity is 5. In S No. 2 I am adding quantity 5 and 12=17. S No 3 I am adding 5 + 12+10=27 and Soo on.

I am sorry if it is a duplicate question. I search google and StackOverflow but didn't get the answer. I am new to MySQL I have added query below. I am new to SQL, any help appreciated,

Thanks in Advance.

CREATE TABLE `stock_table` (
  `ID` int(11) NOT NULL,
  `product_code` varchar(20) NOT NULL,
  `qty` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `stock_table` (`ID`, `product_code`, `qty`) VALUES
(1, 'PO1', 5),
(2, 'PO1', 12),
(3, 'PO1', 10),
(4, 'PO1', 8),
(5, 'PO1', 9),
(6, 'PO1', 16);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
Gagandeep
  • 59
  • 2
  • 10

3 Answers3

1

You need a running sum. If you are using MySQL v 8.0, You can use SUM window function -

SELECT `ID`,
       `product_code`,
       `qty`,
       SUM(`qty`) OVER (PARTITION BY `product_code` ORDER BY `ID`)  Qty_Total
FROM `stock_table`;

fiddle

Ankit Bajpai
  • 13,128
  • 4
  • 25
  • 40
0

You can use correlated subquery to sum up the desired column as the row proceeds by increasing ID value :

select t.*,
       ( select sum(`qty`) from `stock_table` where `ID` <= t.`ID` ) as "Qty Total"
  from `stock_table` t
 order by t.`ID`;

Demo

P.S. : as the sample data has unique product_code value, I didn't need to include the part related to product_code column's matching within the subquery, if it's the case, then consider converting your derived column to :

( select sum(`qty`) 
    from `stock_table` 
   where `ID` <= t.`ID` 
     and `product_code` = t.`product_code` ) as "Qty Total"
Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
0

Your version of MariaDB does not support window functions. That leaves you with two options. One is a correlated subquery; the second is variables.

The first is easier to implement:

select st.*,
       (select sum(st2.qty)
        from stock_table st2
        where st2.product_code = st.product_code and
              st2.id <= st.id
       ) as running_qty
from stock_table st;

For performance, you want an index on stock_table(product_code, id, qty).

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786