KoolReport's Forum

Official Support Area, Q&As, Discussions, Suggestions and Bug reports.
Forum's Guidelines

How to sum two columns on MyReport.php? #2820

Open Daniel opened this topic on on Sep 7, 2022 - 1 comments

Daniel commented on Sep 7, 2022

Hello, I'm trying to get the sum of two columns and group them by another column. I'm using MySQL as database and MySQL Workbench as database admin. The query is quitte simple and works fine in the Workbench:

select statesName, sum(amount), sum(amountInUse) from idrdsystem.resources
join idrdsystem.misc_list_states
on idrdsystem.misc_list_states.statesId = idrdsystem.resources.id_category
join idrdsystem.warehouses
on idrdsystem.warehouses.warehouseId = idrdsystem.resources.resources_warehouseId
where idrdsystem.misc_list_states.tableParent = 'inventory' and idrdsystem.warehouses.warehouseLocation = 2
group by statesName;

The result is something like this:

MyReport.php file:

$this->src("mysql2")->query(
            "select statesName, amount, amountInUse from idrdsystem.resources
            join idrdsystem.misc_list_states
            on idrdsystem.misc_list_states.statesId = idrdsystem.resources.id_category
            join idrdsystem.warehouses
            on idrdsystem.warehouses.warehouseId = idrdsystem.resources.resources_warehouseId
            where idrdsystem.misc_list_states.tableParent = 'inventory' and idrdsystem.warehouses.warehouseLocation =:id"
        )->params(array(
            ":id"=>$this->params["id"]
        ))->pipe(new Group(array(
            "by"=>"statesName",
            "sum"=>"amount",
            "sum"=>"amountInUse"
        )))->pipe($this->dataStore("resourcesStates"));

The problems is that the query only sum the last column ('amountInUse'), not both, I have been looking at the documentation but I haven't found anything similar.

Any help is appreciated.

Sebastian Morales commented on Sep 14, 2022

Just use CalculatedColumn process to sum the two columns into a new one and group by that new column:

        $this->src(...)
        ...
        ->pipe(new CalculatedColumn(array(
            "totalAmount"=>"{amount} + {amountInUse}"
        )))
        ->pipe(new Group(array(
            "by"=>"statesName",
            "sum"=>"totalAmount"
        )))

https://www.koolreport.com/docs/processes/calculatedcolumn/

Build Your Excellent Data Report

Let KoolReport help you to make great reports. It's free & open-source released under MIT license.

Download KoolReport View demo
help needed

None