web
You’re offline. This is a read only version of the page.
close
Skip to main content

Announcements

No record found.

News and Announcements icon
Community site session details

Community site session details

Session Id :
Dynamics 365 Community / Forums / Finance forum / Getting the selected q...
Finance forum

Getting the selected query range value in Variable

(0) ShareShare
ReportReport
Posted on by 436

Hi Experts,

I have one table named "RetailTransactionTable".

In this table we have different customer account.

I want to calculate net amount based on different customers account through Query classes.

I tried like this:

#OCCRetryCount
Query query;
QueryRun queryRun;
QueryBuildDataSource qbds;
QueryBuildRange queryRange;
RetailTransactionTable retailTransactionTable;
real netTotalAmount;


Integer noOfCustomer = _CustomerTransactionContract.parmNoOfCustomer();
query = new Query(SysOperationHelper::base64Decode(_CustomerTransactionContract.parmQuery()));

queryRun = new QueryRun(query);

while (queryRun.next())
{ 
try
{ 
qbds = query.dataSourceTable(tableNum(RetailTransactionTable)); 
qbds.addSelectionField(fieldNum(RetailTransactionTable,netAmount),SelectionField::Sum); 
retailTransactionTable = queryrun.get(tableNum(RetailTransactionTable));

}
catch (Exception::Deadlock)
{
retry;
}
}

info(strFmt("%1",netTotalAmount));
}

Please suggest me the right path

Thanks

Sona Jee

  • Suggested answer
    udaY-ch Profile Picture
    5,186 on at

    Hi,

    Please find the example below to get total using query classes,

    static void Query_Example(Args _args)

    {

       Query q;

       Queryrun qr;

       QueryBuildRange qbr;

       QueryBuildDataSource qbds;

       InventTrans iv;

       Real Total;

       str range;

       // Instantiate the query class.

       q = new query("Inventory_Transactions");

       // Create a data source by using the InventTrans table.

       qbds = q.addDataSource(tablenum(InventTrans));

       // Select only the Qty field, and then sum the Qty field.

       qbds.addSelectionField(fieldnum(InventTrans,Qty),selectionfield::Sum);

       // Set the range to the ItemId field.

       qbr = qbds.addRange(fieldnum(InventTrans,ItemId));  

       // The range for the where statement specifies an 'or' statement.

       qbr.value(strfmt('((%1 == "%2") || (%1 == "%3"))',fieldstr(inventtrans,ItemId),'OL-1500','OL-1000'));

       // The following is the alternative way to enter the range.

       // This also limits the selection on the ItemId values.

       range = strfmt('((ItemId == "%1")||(ItemID =="%2"))',queryvalue('OL-1500'),queryvalue('OL-1000'));

       qbr.value(range);    

       // Create the join to the InventDim table.

       qbds = qbds.addDataSource(tablenum(InventDim));

       // Specify the table relationship.

       qbds.relations(true);

       // Indicate the order mode as the grouping.

       qbds.orderMode(ordermode::GroupBy);

       // Specify the grouping on the InventBatchId field.

       qbds.addSortField(fieldnum(InventDim,InventBatchId));

       // Instantiate the QueryRun class for the form.

       qr = new QueryRun(q);  

           // While there are records in the query, continue.

           while (qr.next())  

           {

              // Set the value of the query to the iv table.

              bufferiv = qr.get(tablenum(InventTrans));

               // Create the value of the total field.

              total =  iv.Qty;  

           }

       // Specify the quantity for the item.

       info(strfmt("Quantity: %1",total));  

       // Indicate the SQL string that is used for the query.

        info (qr.query().dataSourceNo(1).toString());  

    }

    Best,

    Uday.

  • Verified answer
    Martin Dráb Profile Picture
    241,432 Most Valuable Professional on at

    First of all, let me format your code to make it easier to read. Next time, please use the </> button in the rich formatting view to paste source code.

    Query query;
    QueryRun queryRun;
    QueryBuildDataSource qbds;
    
    RetailTransactionTable retailTransactionTable;
    real netTotalAmount;
    
    Integer noOfCustomer = _customerTransactionContract.parmNoOfCustomer();
    query = new Query(SysOperationHelper::base64Decode(_CustomerTransactionContract.parmQuery()));
    
    queryRun = new QueryRun(query);
    
    while (queryRun.next())
    { 
        try
        { 
            qbds = query.dataSourceTable(tableNum(RetailTransactionTable)); 
            qbds.addSelectionField(fieldNum(RetailTransactionTable,netAmount), SelectionField::Sum); 
            retailTransactionTable = queryrun.get(tableNum(RetailTransactionTable));
        }
        catch (Exception::Deadlock)
        {
            retry;
        }
    }
    
    info(strFmt("%1",netTotalAmount));

    Your query currently sum all records. It will return a single record (unless the query already has some grouping), therefore you don't even need a while loop. If you want to get the result, simply assign retailTransactionTable.NetAmount to netTotalAmount.

    If you want a sum for each customer, you must add a field to group by. Like this:

    qbds.addGroupByField(fieldNum(RetailTransactionTable, CustAccount));

    Then you'll get one record for every customer.

  • Sona Jee Profile Picture
    436 on at

    Hi Matin,

    Thanks for the help, it worked.

    Thanks

    Sona Jee

  • Sona Jee Profile Picture
    436 on at

    Hi All,

    I have one doubt how to get top five customers account with their netAmount when the user didn't enter any customer range.

    Thanks

    Sona Jee

  • Suggested answer
    udaY-ch Profile Picture
    5,186 on at

    HI,

    If (!noOfCustomer) //or noOfCustomer == 0

    {

    qbds.addSelectionField(fieldNum(RetailTransactionTable,RecId), SelectionField::Count);

    queryRun.addHavingFilter(qbds, fieldStr(RetailTransactionTable,RecId), AggregateFunction::Count).value('<6');

    }

    Best,

    Uday.

  • Martin Dráb Profile Picture
    241,432 Most Valuable Professional on at

    This would show all customers which has less than six records in RetailTransactionTable, not five customers with the highest total amounts.

    What's needed is sorting by total amount in descending order and taking first five records.

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

November Spotlight Star - Khushbu Rajvi

Congratulations to a top community star!

Forum Structure Changes Coming on 11/8!

In our never-ending quest to help the Dynamics 365 Community members get answers faster …

Dynamics 365 Community Platform update – Oct 28

Welcome to the next edition of the Community Platform Update. This is a status …

Leaderboard > Finance

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans