Class ItemSummaryQuery<T extends PersistedObject & HasCalculableObjectItems>
- Type Parameters:
T- the type of the object whose items are summarized, for example a Simulation
You do not create an instance yourself. Get one from
PublicGroovyAPI.getSimulationSummaryQuery(), set it up
with the methods of this class, and run it with
PublicGroovyAPI.runSummaryQuery(ItemSummaryQuery).
Setting up the query does not read or change any data. The database is read only when
api.runSummaryQuery() runs, and the query never writes data.
Deprecated entry points: the summary queries for Price Lists
(api.getPricelistSummaryQuery()), Live Price Grids (api.getPriceGridSummaryQuery())
and Rebate Records (api.getRebateRecordSummaryQuery()) are deprecated since version 14.0.
For those items, use PublicGroovyAPI.queryApi() with
QapiPriceListLineItem,
QapiPriceGridLineItem or
QapiRebateRecord instead.
Result rows: api.runSummaryQuery() returns a list with one map per group. Each map
contains these keys:
- groupKey: the value of the group-by field. When both an item and a product group-by are set, this is the product field value.
- groupKey2: the item field value. Present only when both an item and a product group-by are set.
- countKey: the number of items in the group. Present only when
setDoCount(boolean)is set totrue. - One key per projection: the lower-case form of
<aggregation>_<field>_<weight>, with spaces removed. For example,addProjection("Cost", "SUM")returns its value undersum_cost_. - totalWeight_ followed by the projection key: the weight used to combine the projection value with other groups.
groupKey is "TOTAL"<T extends PersistedObject & HasCalculableObjectItems>. It combines the values of
all groups. When no group-by is set, it is the only row.
Combining values: the same rules apply to the "TOTAL"<T extends PersistedObject & HasCalculableObjectItems> row and to a group that is
merged over several objects (see addObjectTypedId(String)). SUM, MIN and
MAX values are added up, so the MIN and MAX values of these rows are sums of the
minimums or maximums. AVG values are combined as a weighted average.
Simulation projections: in the query from api.getSimulationSummaryQuery(), every call of
addProjection(String, String) or addProjection(String, String, String) also adds a
projection of the previous value of the field (prefix oldVal_). getProjections() and
getNumberOfProjections() therefore return two projections per call. Each result row then also
contains these keys, for example for addProjection("resultPrice", "SUM"):
oldval_sum_resultprice_: the aggregated previous value, and itstotalWeight_oldval_sum_resultprice_.changeabs_sum_resultprice_: the new value minus the previous value.changepct_sum_resultprice_: that difference divided by the previous value, ornullwhen the previous value is 0.
null. They are
reliable only with one aggregation per field: the query finds the new value by the field name alone, so with
several projections of the same field (for example SUM and AVG of resultPrice), the
change keys compare the previous value with the new value of the last projection of that field.
Example:
def query = api.getSimulationSummaryQuery()
query.addObjectTypedId("12.SIM")
query.setItemGroupBy("attribute1")
query.setDoCount(true)
query.addProjection("resultPrice", "SUM")
def rows = api.runSummaryQuery(query)
def total = rows.find { it.groupKey == "TOTAL" }
- See Also:
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classInternal: generates the identifiers of projections in the database query.static classOne aggregated field of the summary query.static interfaceInternal: used by the server to build the database query. -
Field Summary
Fields -
Constructor Summary
ConstructorsConstructorDescriptionInternal: used by the server to read saved queries.ItemSummaryQuery(String itemToObjectFkName) Internal: used by the server. -
Method Summary
Modifier and TypeMethodDescriptionvoidaddObjectTypedId(String objectTypedId) Adds an object whose items are summarized.voidaddProjection(String field, String aggregation) Adds an aggregated item field to the query.voidaddProjection(String field, String aggregation, String weight) Adds an aggregated item field that is weighted by another item field.voidaddProjection(String fieldPrefix, String field, String aggregation, String weight) Adds an aggregated value that is stored in the attribute extension of the items.voidvoidInternal: used by the server to merge the results of several objects.asListOfMaps(Map<String, Object[]> resultList) Internal: used by the server to build the result ofapi.runSummaryQuery().generateQuerySQL(PersistedObjectService objService, String productSQL, String itemSQL, T calcObj) Internal: used by the server to run the query.getAllItemsFilter(T calcObj) Internal: used by the server to build the database query.Returns the filter that limits which items are summarized.Returns the item field that the query groups by.Internal: used by the server to build the database query.Internal: used by the server to build the database query.intReturns the number of projections (aggregated fields) of the query.Returns the typed Ids of the objects whose items are summarized.Returns the filter on Product fields that limits which items are summarized.Returns the Product field that the query groups by.protected StringInternal: used by the server to build the result ofapi.runSummaryQuery().Returns the projections (aggregated fields) of the query, in the order they were added.getProjectionSQL(PersistedObjectService objService, T calcObj) Internal: used by the server to build the database query.Internal: used by the server to build the database query.booleanChecks whether the query counts the items in each group.booleanChecks whether the query groups the items by both an item field and a product field.booleanChecks whether the query has no group-by.protected voidpostProcessRow(Map<String, Object> row) Internal: used by the server to add computed keys to a result row.protected StringresolveFieldName(AbstractCalculableObjectItem calcObjItem, String fieldNameOrLabel, String itemSqlAlias, PersistedObjectService objService) Internal: used by the server to resolve a field name or label to a database column.voidsetCastCallback(ItemSummaryQuery.QueryGeneratorCallback castCallback) Internal: set by the server before the query runs.voidsetDoCount(boolean doCount) Sets whether the query counts the items in each group.voidsetItemFilter(Filter itemFilter) Limits the summary to the items that match a filter on item fields.voidsetItemGroupBy(String itemGroupBy) Groups the items by the value of an item field.voidsetItemSqlAlias(String itemSqlAlias) Internal: used by the server to build the database query.voidsetItemToObjectFkName(String itemToObjectFkName) Internal: used by the server to build the database query.voidsetObjectTypedIds(List<String> objectTypedIds) Replaces the objects whose items are summarized.voidsetProductFilter(Filter productFilter) Limits the summary to the items whose product matches a filter on Product fields.voidsetProductGroupBy(String productGroupBy) Groups the items by the value of a field of their product.voidsetProjections(List<ItemSummaryQuery.Projection> projections) Internal: used by the server to read saved queries.booleanInternal: used by the server to run the query.
-
Field Details
-
TOTAL_KEY
ThegroupKeyvalue of the result row that holds the totals over all groups.- See Also:
-
-
Constructor Details
-
ItemSummaryQuery
public ItemSummaryQuery()Internal: used by the server to read saved queries. Not for use in logic. Get a query fromPublicGroovyAPI.getSimulationSummaryQuery()instead. -
ItemSummaryQuery
Internal: used by the server. Not for use in logic. Get a query fromPublicGroovyAPI.getSimulationSummaryQuery()instead.- Parameters:
itemToObjectFkName- the item field that holds the Id of the parent object, for examplesimulationId
-
-
Method Details
-
isDualGroupBy
public boolean isDualGroupBy()Checks whether the query groups the items by both an item field and a product field. In that case, each result row has agroupKey(product field value) and agroupKey2(item field value).- Returns:
truewhen bothsetItemGroupBy(String)andsetProductGroupBy(String)are set to a non-empty value
-
isNoGroupBy
public boolean isNoGroupBy()Checks whether the query has no group-by. In that case, the result contains only the "TOTAL"<T extends PersistedObject & HasCalculableObjectItems> row.- Returns:
truewhen neither an item nor a product group-by is set
-
getItemGroupBy
Returns the item field that the query groups by.- Returns:
- the item field name or label, or
nullwhen not set - See Also:
-
setItemGroupBy
Groups the items by the value of an item field. Each distinct value produces one result row. You can combine it withsetProductGroupBy(String); the product field value is then returned asgroupKeyand the item field value asgroupKey2.Example:
def query = api.getSimulationSummaryQuery() query.addObjectTypedId("12.SIM") query.setItemGroupBy("attribute1") query.addProjection("resultPrice", "SUM") def rows = api.runSummaryQuery(query)- Parameters:
itemGroupBy- the name of the item field (for example"attribute1") or its label.nullor an empty string removes the item group-by. If the name or label cannot be resolved to an item field,api.runSummaryQuery()fails with an error.- See Also:
-
isDoCount
public boolean isDoCount()Checks whether the query counts the items in each group.- Returns:
truewhen the result rows containcountKey- See Also:
-
setDoCount
public void setDoCount(boolean doCount) Sets whether the query counts the items in each group. Whentrue, each result row contains the number of items under thecountKeykey. The default isfalse.Example:
def query = api.getSimulationSummaryQuery() query.addObjectTypedId("12.SIM") query.setDoCount(true) query.addProjection("resultPrice", "SUM") def itemCount = api.runSummaryQuery(query)[0].countKey- Parameters:
doCount-trueto count the items in each group
-
getItemToObjectFkName
Internal: used by the server to build the database query. Not for use in logic.- Returns:
- the item field that holds the Id of the parent object
-
setItemToObjectFkName
Internal: used by the server to build the database query. Not for use in logic.- Parameters:
itemToObjectFkName- the item field that holds the Id of the parent object
-
getItemSqlAlias
Internal: used by the server to build the database query. Not for use in logic.- Returns:
- the alias of the item table in the database query
-
setItemSqlAlias
Internal: used by the server to build the database query. Not for use in logic.- Parameters:
itemSqlAlias- the alias of the item table in the database query
-
getAllItemsFilter
Internal: used by the server to build the database query. Not for use in logic.- Parameters:
calcObj- the object whose items are queried- Returns:
- a filter that matches all items of the object
-
getItemFilter
Returns the filter that limits which items are summarized.- Returns:
- the item filter, or
nullwhen not set - See Also:
-
setItemFilter
Limits the summary to the items that match a filter on item fields. The filter is combined with AND with the restriction to the objects added byaddObjectTypedId(String).Example:
def query = api.getSimulationSummaryQuery() query.addObjectTypedId("12.SIM") query.setItemFilter(Filter.equal("attribute1", "EU")) query.addProjection("resultPrice", "SUM") def rows = api.runSummaryQuery(query)- Parameters:
itemFilter- the filter on item fields, ornullto summarize all items- See Also:
-
setCastCallback
Internal: set by the server before the query runs. Not for use in logic.- Parameters:
castCallback- the callback that reads fields as numbers
-
getProductFilter
Returns the filter on Product fields that limits which items are summarized.- Returns:
- the product filter, or
nullwhen not set - See Also:
-
setProductFilter
Limits the summary to the items whose product matches a filter on Product fields. Items are matched to products by Stock Keeping Unit (SKU). When a product filter or a product group-by is set, items without a matching product are left out.Example:
def query = api.getSimulationSummaryQuery() query.addObjectTypedId("12.SIM") query.setProductFilter(Filter.equal("attribute2", "Beef")) query.addProjection("resultPrice", "SUM") def rows = api.runSummaryQuery(query)- Parameters:
productFilter- the filter on Product fields, ornullfor no product filter- See Also:
-
getSanitizedProductGroupBy
Internal: used by the server to build the database query. Not for use in logic.- Returns:
- the product group-by field with all characters except letters, digits and
underscores removed, or
nullwhen not set
-
getProductGroupBy
Returns the Product field that the query groups by.- Returns:
- the Product field name, or
nullwhen not set - See Also:
-
setProductGroupBy
Groups the items by the value of a field of their product. Items are matched to products by Stock Keeping Unit (SKU), and items without a matching product are left out. You can combine it withsetItemGroupBy(String); the product field value is then returned asgroupKeyand the item field value asgroupKey2.Use the Product field name, not its label. Characters other than letters, digits and underscores are removed from the value.
Example:
def query = api.getSimulationSummaryQuery() query.addObjectTypedId("12.SIM") query.setProductGroupBy("attribute3") query.addProjection("resultPrice", "SUM") def rows = api.runSummaryQuery(query)- Parameters:
productGroupBy- the name of the Product field, for example"attribute3".nullor an empty string removes the product group-by.- See Also:
-
getObjectTypedIds
Returns the typed Ids of the objects whose items are summarized.- Returns:
- the list of typed Ids, or
nullwhen no object was added - See Also:
-
setObjectTypedIds
Replaces the objects whose items are summarized. SeeaddObjectTypedId(String).- Parameters:
objectTypedIds- the typed Ids of the objects, for example["12.SIM", "13.SIM"]- See Also:
-
addObjectTypedId
Adds an object whose items are summarized. Add at least one object before you run the query; without an object,api.runSummaryQuery()fails with an error. When you add several objects, their results are merged by group:SUM,MINandMAXvalues are added up (so merged minimums and maximums are sums), andAVGvalues are combined as weighted averages. Objects that do not exist are skipped.Example:
def query = api.getSimulationSummaryQuery() query.addObjectTypedId("12.SIM") query.addObjectTypedId("13.SIM") query.addProjection("resultPrice", "SUM") def rows = api.runSummaryQuery(query)- Parameters:
objectTypedId- the typed Id of the object, for example"12.SIM"- See Also:
-
getProjections
Returns the projections (aggregated fields) of the query, in the order they were added. In a Simulation summary query, this includes theoldVal_projection that eachaddProjection(String, String)call adds automatically (see the class description).- Returns:
- the list of projections, or
nullwhen no projection was added - See Also:
-
setProjections
Internal: used by the server to read saved queries. Not for use in logic. UseaddProjection(String, String)and its overloads instead.- Parameters:
projections- the projections of the query
-
getNumberOfProjections
public int getNumberOfProjections()Returns the number of projections (aggregated fields) of the query. In a Simulation summary query, this is twice the number ofaddProjection(String, String)calls, because each call also adds anoldVal_projection (see the class description).- Returns:
- the number of projections, or 0 when none was added
-
addProjection
Adds an aggregated item field to the query. Add at least one projection before you run the query; without a projection,api.runSummaryQuery()fails with an error. In a Simulation summary query, this also adds a projection of the previous value of the field (see the class description).If the field cannot be found, for example because it was renamed, the projection returns 0.
Example:
def query = api.getSimulationSummaryQuery() query.addObjectTypedId("12.SIM") query.addProjection("resultPrice", "SUM") query.addProjection("attribute5", "AVG") def total = api.runSummaryQuery(query).find { it.groupKey == "TOTAL" } def sum = total["sum_resultprice_"]- Parameters:
field- the name of the numeric item field (for example"attribute5") or its labelaggregation- the aggregation:"SUM","AVG","MIN"or"MAX", in upper case. Any other value, including lower case, makes the query fail or returns values under the wrong keys.- See Also:
-
addProjection
Adds an aggregated item field that is weighted by another item field. With"AVG", the result is the weighted average: the sum of field multiplied by weight, divided by the sum of the weights (0 when the weights add up to 0). With"SUM","MIN"or"MAX", the query aggregates the field multiplied by the weight. In a Simulation summary query, this also adds a projection of the previous value of the field (see the class description).Example:
def query = api.getSimulationSummaryQuery() query.addObjectTypedId("12.SIM") query.addProjection("resultPrice", "AVG", "attribute4") def rows = api.runSummaryQuery(query)- Parameters:
field- the name or label of the numeric item fieldaggregation- the aggregation:"SUM","AVG","MIN"or"MAX", in upper case. Any other value, including lower case, makes the query fail or returns values under the wrong keys.weight- the name or label of the numeric item field to weight by, ornullfor no weighting. If the name or label cannot be resolved to an item field, the weight is ignored and the projection is not weighted.- See Also:
-
addProjection
Adds an aggregated value that is stored in the attribute extension of the items. The query reads the attribute-extension entry named byfieldPrefixfollowed by the resolved field name. For example, in a Simulation the prefix"oldVal_"reads the previous value of the field. The Simulation summary query already adds theoldVal_projection for everyaddProjection(String, String)call, so do not add it yourself: anoldVal_projection without the matchingaddProjection(field, ...)call makesapi.runSummaryQuery()fail.With
"AVG"and a weight, the prefix is also added to the weight field in the average, but thetotalWeight_value (used to combine groups, objects and the "TOTAL"<T extends PersistedObject & HasCalculableObjectItems> row) is the sum of the weight field without the prefix. With"SUM","MIN"or"MAX", the weight field is read without the prefix.Example, reading the previous value that the Simulation summary query adds automatically:
def query = api.getSimulationSummaryQuery() query.addObjectTypedId("12.SIM") query.addProjection("resultPrice", "SUM") def total = api.runSummaryQuery(query).find { it.groupKey == "TOTAL" } def oldSum = total["oldval_sum_resultprice_"]- Parameters:
fieldPrefix- the attribute-extension prefix, for example"oldVal_". Pass an empty string for a regular item field.field- the name or label of the numeric item fieldaggregation- the aggregation:"SUM","AVG","MIN"or"MAX", in upper case. Any other value, including lower case, makes the query fail or returns values under the wrong keys.weight- the name or label of the numeric item field to weight by, ornullfor no weighting- See Also:
-
generateQuerySQL
public String generateQuerySQL(PersistedObjectService objService, String productSQL, String itemSQL, T calcObj) Internal: used by the server to run the query. Not for use in logic.- Parameters:
objService- the server service that resolves fieldsproductSQL- the condition generated from the product filter, ornullitemSQL- the condition generated from the item filtercalcObj- the object whose items are queried- Returns:
- the database query, or
nullwhen there are no projections or no object
-
withProduct
public boolean withProduct()Internal: used by the server to run the query. Not for use in logic.- Returns:
truewhen a product filter or a product group-by is set
-
aggregate
Internal: used by the server to merge the results of several objects. Not for use in logic.- Parameters:
results- the merged result rows by group key, updated in placequeryResults- the rows returned by the database for one object
-
addTotal
Internal: used by the server to add the "TOTAL"<T extends PersistedObject & HasCalculableObjectItems> row. Not for use in logic.- Parameters:
results- the merged result rows by group key, updated in place
-
getProjectionName
Internal: used by the server to build the result ofapi.runSummaryQuery(). Not for use in logic.- Parameters:
p- the projection- Returns:
- the key of the projection value in the result rows
-
asListOfMaps
Internal: used by the server to build the result ofapi.runSummaryQuery(). Not for use in logic.- Parameters:
resultList- the merged result rows by group key- Returns:
- one map per result row, keyed as described in the class description
-
postProcessRow
Internal: used by the server to add computed keys to a result row. Not for use in logic.- Parameters:
row- the result row
-
resolveFieldName
protected String resolveFieldName(AbstractCalculableObjectItem calcObjItem, String fieldNameOrLabel, String itemSqlAlias, PersistedObjectService objService) Internal: used by the server to resolve a field name or label to a database column. Not for use in logic.- Parameters:
calcObjItem- an item of the summarized objectfieldNameOrLabel- the field name or label to resolveitemSqlAlias- the alias of the item tableobjService- the service used to read the attribute metadata- Returns:
- the resolved field name, or
nullif it cannot be resolved
-
getProjectionSQL
Internal: used by the server to build the database query. Not for use in logic.- Parameters:
objService- the server service that resolves fieldscalcObj- the object whose items are queried- Returns:
- the aggregate part of the database query, or
nullwhen there are no projections or no object
-