0

In MySQLThere is a table include ID, DAT, AMN, FLWC, FLWD, TYP. I would like to sort table by DAT and ID (DAT is first keyword in sort) then update FLWC and FLWD from previous record depend on TYP. for example if 0:previous record and 1:current record then:

if typ1==d then (flwc1=flwc0 AND flwd1=flwd0+amn1)
if typ1==c then (flwc1=flwc0+amn AND flwd1=flwd0)

You can see that flwc and flwd will be set to next record and one of them will be sum to AMN depend on TYP value.

Table before changes:

-- id__dat__amn__flwc__flwd__typ
-- 1   10   100  0     0     d
-- 2   11   200  0     0     c
-- 3   12   300  0     0     d
-- 4   13   400  0     0     c
-- 5   14   500  0     0     d
-- 6   15   600  0     0     c
-- 7   16   700  0     0     d

Table after UPDATE:

-- id__dat__amn__flwc__flwd__typ
-- 1   10   100  0     100   d
-- 2   11   200  200   100   c
-- 3   12   300  200   400   d
-- 4   13   400  600   400   c
-- 5   14   500  600   900   d
-- 6   15   600  1200  900   c
-- 7   16   700  1200  1600  d

I did it in MS SQL server but MySQL seems is poor in such case (set value to parameter during update query), solution in MS SQL Server:

declare @sumc decimal
declare @sumd decimal
set @sumc=0
set @sumd=0

update myTable set 
    @sumc+= case typ when 'c' then amn else 0 end, flwc=@sumc,
    @sumd+= case typ when 'd' then amn else 0 end, flwd=@sumd

I need the above query in MySQL. Thanks

2 Answers 2

0

It can be done with MySQL.

An example that could be useful.

table:

CREATE TABLE `test` (
    `Id` INT(11) NOT NULL AUTO_INCREMENT,
    `Incrementar` INT(11) NOT NULL,
    PRIMARY KEY (`Id`)
);

Inserting test records:

INSERT INTO `test` (`Incrementar`) VALUES (0);
INSERT INTO `test` (`Incrementar`) VALUES (0);
INSERT INTO `test` (`Incrementar`) VALUES (0);
INSERT INTO `test` (`Incrementar`) VALUES (0);

UPDATE:

SET @tempVariable = 1;

UPDATE test SET Incrementar = (@tempVariable:=@tempVariable+1)

Result:

Id  Incrementar
1   2
2   3
3   4
4   5
3
  • So I need at least one temp field (Incrementar) ?
    – Hamid
    Jul 25, 2014 at 21:14
  • You look at my other answer.
    – Barto
    Jul 25, 2014 at 21:38
  • But this answer is better and I did my job by it. Thanks
    – Hamid
    Jul 26, 2014 at 21:13
0

My previous response was an example. What you need is:

SET @sumc=0; 
SET @sumd=0;

UPDATE myTable SET 
 flwc= (SELECT @sumc := IF(typ = 'c', amn + @sumc, @sumc)),
 flwd= (SELECT @sumd := IF(typ = 'd', amn + @sumd, @sumd));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.