{"title":"Aggregating data in query objects","url":"https://jonas-paprotka.de/docs/dev-itpro/developer/devenv-query-totals-grouping/","by":"JOP-AL","license":"Copyright (c) Microsoft Corporation. CC BY 4.0, https://creativecommons.org/licenses/by/4.0/; code samples MIT. From https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-query-totals-grouping, MicrosoftDocs/dynamics365smb-devitpro-pb at 828b6ee (2026-11-19). Changed: includes filled in, links to this site, and for agents shortened without dropping a fact.","credit":"Microsoft Corporation, CC BY 4.0","origin":"https://learn.microsoft.com/en-us/dynamics365/business-central/dev-itpro/developer/devenv-query-totals-grouping","source":{"name":"Business Central developer and IT pro docs","repo":"https://github.com/MicrosoftDocs/dynamics365smb-devitpro-pb","commit":"828b6ee72fcd75755627cd6011f3d20899217ab2","date":"2026-11-19"},"checked":"2026-11-19","description":"Do calculations on the fields of a column and return the calculated value in the dataset. Know the Dynamics NAV Total methods for running queries.","date":"2024-05-03","meta":{"topic":"concept-article"},"outline":[{"level":1,"title":"Aggregating data in query objects","slug":"aggregating-data-in-query-objects","at":0,"chars":9535},{"level":2,"title":"Setting up an aggregate method for a query column","slug":"setting-up-an-aggregate-method-for-a-query-column","at":1396,"chars":1006},{"level":2,"title":"Sample Query","slug":"sample-query","at":2402,"chars":1601},{"level":2,"title":" Sum","slug":"sum","at":4003,"chars":623},{"level":2,"title":" Average","slug":"average","at":4626,"chars":652},{"level":2,"title":" Min","slug":"min","at":5278,"chars":693},{"level":2,"title":" Max","slug":"max","at":5971,"chars":697},{"level":2,"title":" Count","slug":"count","at":6668,"chars":1094},{"level":2,"title":"Using a query to get distinct values","slug":"using-a-query-to-get-distinct-values","at":7762,"chars":1286},{"level":2,"title":"Contributors","slug":"contributors","at":9048,"chars":243},{"level":2,"title":"Related information","slug":"related-information","at":9291,"chars":244}],"text":"# Aggregating data in query objects\nIn a query object, you can use the properties/devenv-method-property to do a calculation on the fields of a column and return the calculated value in the dataset. For example, you can sum all the fields in a column or find the average value. The Method property is set on column controls and can be set to any of the following aggregate methods.\nAggregate method|Description\n#Sum|Calculates the sum of the values of the field in the designated column for all records that are selected as part of the grouped set.\n#Average|Calculates the average value of the field in the designated column for all records that are selected as part of the grouped set.<br /><br /> When averaging fields that have an integer data type \\(such as Integer or BigInteger\\), integer division is used. The result isn't rounded, and the remainder is discarded. For example, 5÷2=2 instead of 2.5 \\(or 2 1/2\\).\nMin<#Minimum>|Retrieves the lowest value of the field in the designated column for all records that are selected as part of the grouped set.\nMax<#Maximum>|Retrieves the highest value of the field in the designated column for all records that are selected as part of the grouped set.\n#Count|Returns the number of records that are selected as part of the grouped set. <br /> You can return a set of #using-a-query-to-get-distinct-values values from a table using a Count method.\n## Setting up an aggregate method for a query column\nExcept for the Count method, you can only use an aggregate method \\(Sum, Average, Min, and Max\\) on a field that has a numeric data type of methods-auto/decimal/decimal-data-type, methods-auto/integer/integer-data-type, methods-auto/biginteger/biginteger-data-type, or methods-auto/duration/duration-data-type. To set up an aggregate on a column, you set the column's properties/devenv-method-property.\n```al\ncolumn(Name; Field)\n{\n    Method = Sum|Average|Min|Max|Count;\n}\n```\nSetting an aggregate method on a column will automatically group the resultant data set by the other columns in the query. Records that have matching values for the other columns are grouped together into a single row in the results. The aggregate method is then applied against the group and a summary value returned in the row. It's similar to the GROUP BY clause in SQL SELECT statements.\nThe aggregate methods and grouping are further explained in the following sections.\n## Sample Query\nThe following sample query object retrieves the number of line items in every sales order for each customer. The query links the Customer table and the Sales Line table. In its current state, the Method property is commented out so it doesn't implement any aggregate method.\n```al\nquery 50101 \"Customer_Sales_Quantity\"\n{\n    QueryType = Normal;\n    // Sorts the results in descending order\n    OrderBy = descending(Qty);\n\n    elements\n    {\n        dataitem(C; Customer)\n        {\n            column(Customer_Number; \"No.\")\n            {\n            }\n\n            column(Customer_Name; Name)\n            {\n            }\n\n            dataitem(SL; \"Sales Line\")\n            {\n                DataItemLink = \"Sell-to Customer No.\" = c.\"No.\";\n                SqlJoinType = InnerJoin;\n\n                column(Qty; Quantity)\n                {\n                    // Change the value of the property to perform a different aggregate method on grouped columns:\n                    // Sum, Average, Max, Min, or Count\n                    // Method = Sum|Average|Min|Max|Count;\n                }\n            }\n        }\n    }\n}\n```\nThe following table represents a simplified version of the resulting dataset for the sample query.\nCustomer_Number|Customer_Name|Qty\n20000|Selangorian Ltd.|400\n30000|Blanemark Hifi|350\n20000|Selangorian Ltd.|300\n40000|Deerfield Graphics|250\n20000|Selangorian Ltd.|200\n30000|Blanemark Hifi|150\nThe following sections explain how you can modify the query to implement the different aggregate methods by changing the value of the properties/devenv-method-property.\n##  Sum\nThe Sum method adds the values of all fields for the specified column within a group. To set up a Sum method on the Quantity column of the sample query, set the Method property to Sum. The query is automatically grouped by the No. and Name columns.\n```al\n...\ncolumn(Qty; Quantity)\n{\n    Method = Sum;\n}\n...\n```\nLooking at the sample query, you can use Sum method to get the total number of items in sales orders for each customer. The following table illustrates the resulting dataset for the query.\nCustomer_Number|Customer_Name|Qty\n20000|Selangorian Ltd.|900\n30000|Blanemark Hifi|500\n40000|Deerfield Graphics|250\n##  Average\nThe Average method calculates the average value of the fields in the column within a group. To set up an Average method on the Quantity column of the sample query, set the Method property to Average. The query is automatically grouped by the No. and Name columns:\n```al\n...\ncolumn(Qty; Quantity)\n{\n    Method = Average;\n}\n...\n```\nLooking at the sample query, you can use Average method to get the average number of items in sales orders for each customer. The following table illustrates the resulting dataset for the query.\nCustomer_Number|Customer_Name|Qty\n20000|Selangorian Ltd.|300\n30000|Blanemark Hifi|250\n40000|Deerfield Graphics|250\n##  Min\nThe Min method retrieves the lowest value of fields in the column within a group. To set up a Min method on the Quantity column of the sample query, set the Method property to Min. The name of the Quantity column automatically changes to Min_Quantity and the query is automatically grouped by the No. and Name columns:\n```al\n...\ncolumn(Qty; Quantity)\n{\n    Method = Min;\n}\n...\n```\nLooking at the sample query, you can use Min method to get the least number of items in sales orders for each customer. The following table illustrates the resulting dataset for the query.\nCustomer_Number|Customer_Name|Qty\n40000|Deerfield Graphics|250\n20000|Selangorian Ltd.|200\n30000|Blanemark Hifi|150\n##  Max\nThe Max method retrieves the highest value of fields in the column within a group. To set up a Max method on the Quantity column of the sample query, set the Method property to Max. The name of the Quantity column automatically changes to Max_Quantity and the query is automatically grouped by the No. and Name columns:\n```al\n...\ncolumn(Qty; Quantity)\n{\n    Method = Max;\n}\n...\n```\nLooking at the sample query, you can use Max method to get the greatest number of items in sales orders for each customer. The following table illustrates the resulting dataset for the query.\nCustomer_Number|Customer_Name|Qty\n20000|Selangorian Ltd.|400\n30000|Blanemark Hifi|350\n40000|Deerfield Graphics|250\n##  Count\nThe Count method returns the number of records from the data item table that comprise a group in the dataset. Unlike the other aggregate methods, the Count method is not associated with a specific column. Records are identified and counted based on the primary key of the data item table. Referring to the sample query, you can use a Count method to get the number of open sales orders per customer.\nTo set up a Count method in the sample query, the column element definition cannot include a source table; only a name. Therefore, you can delete the reference to the Quantity field in the `column(Qty; Quantity)` element and set the Methodproperty to Count:\n```al\n...\ncolumn(Qty)\n{\n    Method = Count;\n}\n\n```\nLooking at the sample query, you can use Count method the number of sales orders for each customer. The following table illustrates the resulting dataset for the query.\nCustomer_Number|Customer_Name|Qty\n20000|Selangorian Ltd.|3\n30000|Blanemark Hifi|2\n40000|Deerfield Graphics|1\nIn SQL SELECT statements, the Count method corresponds to a COUNT\\(*\\) or COUNT\\(field\\) clause.\n## Using a query to get distinct values\nWhen working with table data, you might need to get a list of distinct values from the table (in SQL, this would correspond to a SELECT DISTINCT statement). This operation isn't supported out-of-the-box in AL, but you can do it with a query using an aggregation.\nThis AL example code shows how you can encode distinct into a query using an aggregation.\n```al\nquery 50150 DistinctValuesQuery\n{\n    Caption = 'My Query';\n    QueryType = Normal;\n\n    elements\n    {\n        dataitem(CustLedgerEntry; \"Cust. Ledger Entry\")\n        {\n            column(CustomerNo; \"Customer No.\")\n            {\n            }\n            column(DocumentType; \"Document Type\")\n            {\n            }\n            column(Count)\n            {\n                Method = Count;\n            }\n        }\n    }\n}\n```\nThis AL example code shows how you can then query for the distinct values (note that the Count column isn't used here).\n```al\ntrigger OnAction()\nvar\n    MyQuery: Query DistinctValuesQuery;\n    CombinationText: Text;\nbegin\n    if MyQuery.Open() then begin\n        while MyQuery.Read() do\n            CombinationText += MyQuery.CustomerNo + '-' + Format(MyQuery.DocumentType) + '; ';\n        MyQuery.Close();\n    end;\n\n    Message(CombinationText);\nend;\n```\n## Contributors\nThis article is maintained by Microsoft. Parts of the examples were originally written by the following contributor.\n Teddy Herryanto<https://www.linkedin.com/in/teddyherryanto/> | Business Central Techno Functional Consultant\n## Related information\nproperties/devenv-method-property\ndevenv-query-object\nFiltering Queries<devenv-query-filters>\nAggregating Data<devenv-query-totals-grouping>\nhttps://learn.microsoft.com/sql/t-sql/functions/aggregate-functions-transact-sql"}