Search code examples
axaptadynamics-ax-2012x++

How to sum a field using some conditions in Axapta?


I have a user table like this

  ID     Date        Value
  ---------------------------
  1001   31 01 14    2035.1
  1002   31 01 14    1384.65
  1003   31 01 14    1011.1
  1004   31 01 14    1187.04
  1001   28 02 14    2035.1
  1002   28 02 14    1384.65
  1003   28 02 14    1011.1
  1004   28 02 14    1188.86
  1001   31 03 14    2035.1
  1002   31 03 14    1384.65
  1003   31 03 14    1011.1
  1004   31 03 14    1188.86
  1001   30 04 14    2066.41
  1002   30 04 14    1405.95
  1003   30 04 14    1026.66
  1004   30 04 14    1207.15

And I want to make a sum from this table like this

  ID     Date        Value       Total
  ---------------------------------------
  1001   31 01 14    2035.1     2035.1
  1002   31 01 14    1384.65    1384.65
  1003   31 01 14    1011.1     1011.1
  1004   31 01 14    1187.04    1187.04
  1001   28 02 14    2035.1     4070.2
  1002   28 02 14    1384.65    2769.3
  1003   28 02 14    1011.1     2022.2
  1004   28 02 14    1188.86    2375.9
  1001   31 03 14    2035.1     6105.3
  1002   31 03 14    1384.65    4153.95
  1003   31 03 14    1011.1     3033.3
  1004   31 03 14    1188.86    3564.76
  1001   30 04 14    2066.41    8171.71
  1002   30 04 14    1405.95    5180.61
  1003   30 04 14    1026.66    4059.96
  1004   30 04 14    1207.15    4771.91

I have id, for each id for the first month it should write it is value for total and for second month of that id, it should add the value of first month + second month and it should go on like this. How can I do this summation in X++?

Can anyone help me?


Solution

  • It can be done as a display method on the table:

    display Amount total()
    {
        return (select sum(Value) of Table 
                    where Table.Id == this.Id &&
                          Table.Date <= this.Date).Value;
    }
    

    Change the table and field names to your fit.

    This may not be the fastest way to do it though. In say a report context, it might be better to keep a running total for each id (in a map).

    Also it can be done in a select like this:

    Table table1, table2
    while select table1
        group Date, Id, Value
        inner join sum(Value) of table2 
        where table2.Id == table1.Id &&
              table2.Date <= table1.Date
    {
        ...
    }
    

    You need to group on the wanted fields, because it is an aggregate select.