Sub topic 6
Measures, Currency and Unit Semantics, and Aggregation
This chapter assumes you can read a CDS view entity, know what an association is, and have seen the cube and dimension annotations from the previous chapters. You should also be comfortable with SQL aggregates such as SUM and GROUP BY. The chapter covers how a cube field becomes a measure, how amounts and quantities stay tied to their currency or unit, and how aggregation behaves when a query groups the data in different ways.
What makes a field a measure
A cube view contains two kinds of fields. Characteristics (such as customer, product or country) are used to group and filter. Measures (such as net amount or ordered quantity) are numbers that you add up, count or average. The analytical engine decides which is which from annotations. A numeric column with no aggregation annotation is treated as a plain attribute, and you can't sum it in a query.
A measure needs two things:
- An aggregation behavior, set with
@DefaultAggregation. - A semantic link to a currency or unit, set with
@Semantics, when the value has one.
Here is the cube from the earlier chapter, with the measure fields marked:
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Sales item cube'
@Analytics.dataCategory: #CUBE
define view entity ZI_SalesItemCube
as select from zsales_item
association [0..1] to ZI_CustomerDim as _Customer
on $projection.CustomerId = _Customer.CustomerId
{
key item_uuid as ItemUuid,
@ObjectModel.foreignKey.association: '_Customer'
customer_id as CustomerId,
@Semantics.currencyCode: true
currency as Currency,
@DefaultAggregation: #SUM
@Semantics.amount.currencyCode: 'Currency'
net_amount as NetAmount,
_Customer
}NetAmount carries @DefaultAggregation: #SUM, so the engine adds it up whenever rows are grouped. @Semantics.amount.currencyCode: 'Currency' names the field that holds the currency key for this amount. Currency is flagged with @Semantics.currencyCode: true so the engine knows it is a currency code and not an ordinary text field.
Aggregation types
@DefaultAggregation accepts several values. The most common are in this table.
| Value | Result | Typical use |
|---|---|---|
| `#SUM` | Total of all values in the group | Revenue, cost, quantity |
| `#MIN` | Smallest value | Earliest price, lowest stock |
| `#MAX` | Largest value | Highest discount |
| `#AVG` | Average of values (supported in some contexts) | Rates, scores |
| `#NONE` | No aggregation, value is read as is | Fields that must not be added |
| `#FORMULA` | Calculated from other measures | Ratios and margins |
Check the release documentation for your system before relying on #AVG. Averages are a frequent source of wrong totals, because the average of averages differs from the average of the underlying rows. When you need a true weighted average, store the numerator and denominator as separate #SUM measures and calculate the ratio at query level or with a formula.
Currency semantics
An amount without a currency is ambiguous. Ten units of "something" in one row and ten in another cannot be added safely if one is euros and the other is US dollars. The @Semantics.amount.currencyCode annotation prevents this mistake from going unnoticed.
When a query groups rows and the amounts share one currency, the engine returns the sum with that currency. When the group contains mixed currencies, the engine cannot add them. It returns the amount as a multi-currency result, which front ends display as a value with an asterisk or a mixed marker instead of a misleading number. This is deliberate. A silently wrong total is worse than a visibly incomplete one.
The reference field must be in the same view, and it must be in the field list. If you leave out the currency field from the select list, activation fails or the annotation has no effect.
The data types matter too. Amount fields should use a decimal type with a currency reference, such as abap.curr in the underlying table. Currency fields should use abap.cuky. If your source table stores amounts as plain floating-point or integer values, convert them in the view with a cast to the right type.
Converting currencies
Often you want one currency across a whole report, for example the company's group currency. CDS provides the function currency_conversion for this. It works inside a view entity and needs the source amount, source currency, target currency and a date for the exchange rate.
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Sales item cube with converted amount'
@Analytics.dataCategory: #CUBE
define view entity ZI_SalesItemConvCube
with parameters
P_TargetCurrency : abap.cuky( 5 )
as select from zsales_item
{
key item_uuid as ItemUuid,
@Semantics.currencyCode: true
$parameters.P_TargetCurrency as TargetCurrency,
@DefaultAggregation: #SUM
@Semantics.amount.currencyCode: 'TargetCurrency'
currency_conversion(
amount => net_amount,
source_currency => currency,
target_currency => $parameters.P_TargetCurrency,
exchange_rate_date => posting_date,
error_handling => 'SET_TO_NULL'
) as NetAmountInTarget
}The error_handling argument decides what happens when no exchange rate exists. 'SET_TO_NULL' returns null for that row and the query continues. 'FAIL_ON_ERROR' stops the query. Choose deliberately. A null silently drops the row from a sum, while a failure surfaces the data problem at once.
Conversion is evaluated per row before aggregation. This is the correct order for financial figures, but it costs more than converting a total. Large cubes with currency conversion are a common source of slow queries, which a later chapter on performance revisits.
Unit of measure semantics
Quantities follow the same pattern as amounts. A quantity needs a unit key, and the annotation links the two.
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Delivery item cube'
@Analytics.dataCategory: #CUBE
define view entity ZI_DeliveryItemCube
as select from zdelivery_item
{
key delivery_uuid as DeliveryUuid,
@Semantics.unitOfMeasure: true
unit as DeliveryUnit,
@DefaultAggregation: #SUM
@Semantics.quantity.unitOfMeasure: 'DeliveryUnit'
quantity as DeliveredQuantity
}The rules mirror those for currency. A group with one unit returns a total with that unit. A group with several units, such as kilograms and pieces, cannot be added and shows as mixed. The underlying table should use abap.quan for the quantity and abap.unit for the unit key.
Unit conversion is available through unit_conversion, which works like currency_conversion but takes a source unit, a target unit and the material or other context needed to look up the conversion factor. Use it when a report must compare quantities across units, for example converting everything to kilograms.
Calculated measures
Not every measure exists as a column. Margin, share of total and price per unit are derived. You have two places to define them.
- In the cube, using a calculation in the select list and
#FORMULA. This makes the measure available to every query on the cube. - In a query, using calculated key figures. This keeps the logic with the one report that needs it.
Prefer the query level for measures that only one report uses. Put a calculation in the cube when several queries need the same definition, so that the number means the same thing everywhere.
A common error is to write a ratio in the cube with #SUM. The engine then adds the ratios of individual rows, which is nearly always wrong. A ratio must be computed after the numerator and denominator have been summed.
How aggregation flows through a query
The order of operations explains most surprising results. The engine builds the result in stages.
Two consequences follow:
- Row-level expressions run before grouping. Conversions and per-row calculations see individual rows.
- Ratios and formulas run after grouping. They see totals, which is what you want for a margin.
Grouping depends on which characteristics appear in the query. If the query shows customer on the rows, the engine groups by customer. If you remove customer, the same measure is summed over all customers. The measure definition does not change, only the level of detail does.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Amount shows no currency in the report | The `currencyCode` reference is missing or names a field not in the select list | Add the currency field and correct the annotation |
| Total shows a mixed marker | Rows in the group use different currencies | Convert to one currency, or add currency to the rows |
| Ratio totals look wrong | Ratio defined with `#SUM` | Sum numerator and denominator, then divide |
| Measure cannot be added in a query | No `@DefaultAggregation` set | Add `#SUM` or another aggregation |
| Totals shrink after conversion | Missing rates with `'SET_TO_NULL'` | Check the rate table or use `'FAIL_ON_ERROR'` while testing |
| Quantity totals mix units | Unit field not linked or not exposed | Add `@Semantics.quantity.unitOfMeasure` and expose the unit |
Putting it together
A well-modeled measure has a defined aggregation, a semantic reference to its currency or unit, a data type that supports both, and a clear decision about where any calculation lives. When these four are in place, the same cube can serve many queries and every front end shows consistent totals. The next chapter builds on this by placing these measures on the axes of an analytical query view.
Exercise
A cube has a field unit_price with @DefaultAggregation: #SUM, and a field quantity with #SUM. A query shows the sum of unit_price per product and the numbers look far too high. What is the problem, and how would you provide a correct average price per product?
Show answer
Unit price is not additive, so #SUM adds prices across rows and gives a meaningless total. Provide the revenue amount (price times quantity per row) and the quantity as two #SUM measures, then define the average price as a calculated measure that divides the summed revenue by the summed quantity. The division happens after aggregation, so the result is a true weighted average.
Exercise
A report shows a net amount total with a mixed-currency marker instead of a number. Name two ways to get a single numeric total, and one risk of each.
Show answer
First, convert all rows to one target currency with currency_conversion and expose the target currency as the reference field. The risk is missing exchange rates, which with 'SET_TO_NULL' drop rows from the total without warning. Second, add the currency characteristic to the query rows so each currency gets its own total. The risk is that the user sees several totals and no combined figure.