Sub topic 7
Building an analytical query view
This chapter covers the consumption layer of the Virtual Data Model: the analytical query view. It assumes you can read basic SQL (SELECT, JOIN, GROUP BY, aggregate functions) and know S/4HANA business objects such as sales orders and customers. It also assumes you have met CDS view entities, associations, and the cube and dimension annotations from earlier chapters. You should also know the difference between transactional (OLTP) and analytical (OLAP) workloads.
What a query view is
A query view is a CDS view entity that sits on top of a cube. It defines one analytical question: which fields appear on rows, which on columns, which are filters, and how measures are aggregated. The cube holds the data model. The query shapes it for a report or a tile.
The query does not store data. At run time the analytical engine reads the cube, aggregates on the database and returns a result set shaped by the rows and columns you declared. Because the query is a thin definition, you can build many queries on one cube.
The query belongs to the consumption layer, so the usual naming convention is a ZC_ prefix (C_ in SAP's own content). Interface views (I_) and cubes sit below it.
The minimal query
The example below is the query used throughout this tutorial. It reads the cube ZI_SalesItemCube, places the customer on the rows and the net amount on the columns.
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Net amount by customer'
@Analytics.query: true
define view entity ZC_NetAmountByCustomer
as select from ZI_SalesItemCube
{
@AnalyticsDetails.query.axis: #ROWS
CustomerId,
@AnalyticsDetails.query.axis: #COLUMNS
NetAmount
}Four things make this a query.
@Analytics.query: truemarks the view as an analytical query. Without it the view is an ordinary CDS view that happens to read a cube, and analytical front ends will not list it.as select from ZI_SalesItemCubereads from a cube (a view with@Analytics.dataCategory: #CUBE). Reading from a cube is what gives the query its measure and dimension semantics.@AnalyticsDetails.query.axisassigns each field to an axis.#ROWSand#COLUMNSare the two axes that carry data.#FREEmakes a field available for the user to drag in later.@AccessControl.authorizationCheck: #CHECKstates that an access control must exist for this view. A later chapter covers writing it.
The select list contains no SUM and no GROUP BY. The aggregation comes from @DefaultAggregation: #SUM on NetAmount in the cube. The grouping comes from the fields you place on the rows. The query inherits both.
Axes: rows, columns and free characteristics
Every field in a query plays one of three roles.
| Axis value | Role in the result | Typical use |
|---|---|---|
| `#ROWS` | Characteristic shown down the left side | Customer, country, month |
| `#COLUMNS` | Measure (or characteristic) shown across the top | Net amount, quantity |
| `#FREE` | Characteristic not shown at first, available for drill-down | Country, product group |
A characteristic is a descriptive field such as a customer or a country. A measure is a numeric field that can be aggregated. The convention is characteristics on rows and free, measures on columns. Placing a characteristic on columns is possible but unusual.
Here is a richer version with a free characteristic, a text element and a filter.
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Net amount by customer and country'
@Analytics.query: true
define view entity ZC_NetAmountByCustomerCountry
as select from ZI_SalesItemCube
{
@AnalyticsDetails.query.axis: #ROWS
@AnalyticsDetails.query.display: #KEY_TEXT
CustomerId,
@AnalyticsDetails.query.axis: #FREE
_Customer.Country as Country,
@AnalyticsDetails.query.axis: #COLUMNS
NetAmount,
@Consumption.filter.selectionType: #RANGE
@AnalyticsDetails.query.axis: #FREE
Currency
}Three details in this version are worth noting.
@AnalyticsDetails.query.display: #KEY_TEXTshows the key and its text together, for example1000 Acme Ltd. The text comes from the field marked@Semantics.text: truein the dimension. The cube must reach the dimension through the association_Customerfor this to work._Customer.Country as Countryreads an attribute through the association. The association is resolved only when the field is selected.@Consumption.filter.selectionType: #RANGElets the user filter with ranges and multiple values rather than a single value.
How the result is calculated
Aggregation happens in the database, not in the ABAP application server. The sequence is:
- A front end sends a request with the query name, the chosen axes and any filters.
- The analytical engine builds an SQL statement from the query, the cube and the associations it needs.
- The access control adds its conditions to that statement.
- SAP HANA groups by the row characteristics, applies the aggregation and returns the rows.
- The front end formats the result, including currency and text.
Only the associations the query actually uses become joins. If a user never drills into country, the join to the customer dimension for that attribute is not needed. This is one reason to keep the cube thin and put descriptive data behind associations.
Restricting and calculating inside a query
A query can do more than reorder fields. Common additions are listed below.
| Need | Mechanism |
|---|---|
| Fixed filter on every execution | A `where` clause in the query view |
| Value the user must supply | A variable with `@Consumption.derivation` or a parameter on the view |
| Calculated measure | An expression in the select list, with a name and a type |
| Restricted measure | A measure limited to a characteristic value, such as net amount for one country |
Here is a query with a fixed filter and a calculated measure. It assumes the cube also exposes a Quantity field with a unit; a calculated measure must stay in the same unit or currency semantics as its inputs.
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Net amount per unit'
@Analytics.query: true
define view entity ZC_NetAmountPerUnit
as select from ZI_SalesItemCube
{
@AnalyticsDetails.query.axis: #ROWS
CustomerId,
@AnalyticsDetails.query.axis: #COLUMNS
NetAmount,
@AnalyticsDetails.query.axis: #COLUMNS
Quantity
}
where Currency = 'EUR'Take care with calculated measures. A ratio such as net amount divided by quantity is not additive. If you computed it per row and then summed it, the total would be wrong. The analytical engine calculates the ratio after it aggregates numerator and denominator, but only when the calculation is defined in the query rather than in a lower view. Define ratios in the query, and keep additive base measures in the cube.
Common errors
These are the problems that appear most often when you build your first queries.
- The query is missing from the Fiori apps. Check
@Analytics.query: true. Then check that the underlying cube has@Analytics.dataCategory: #CUBEand that both views are activated without warnings. - Amounts appear without currency or are not summed. The measure in the cube needs
@Semantics.amount.currencyCodepointing at a field annotated@Semantics.currencyCode: true, and the query must include or filter that currency field. Mixed currencies cannot be summed into one number, so the engine shows them separately. - Texts do not show. The dimension needs one field with
@Semantics.text: true, and the cube must have a foreign key association to the dimension through@ObjectModel.foreignKey.association. - Users see all data or none. With
#CHECK, a missing access control means no one gets data. With#NOT_REQUIRED, everyone sees everything. Neither should be used by accident. - Wrong totals on ratios. The calculation was placed in a lower view and evaluated per row. Move it to the query.
- Fields on the wrong axis. A measure on
#ROWSis treated as a characteristic, and the result is grouped by its value. Put measures on#COLUMNS.
Testing a query
You can test a query without a front end. In the ABAP development tools for Eclipse, open the query and use the data preview (F8). The preview runs the same SQL the engine builds, which makes it useful for checking grouping and totals against the SQL you would write by hand.
To check a total, write the equivalent SQL against the table and compare.
SELECT customer_id, currency, SUM(net_amount) AS net_amount
FROM zsales_item
GROUP BY customer_id, currencyIf the preview and this statement disagree, check three things: filters in the query, filters added by the access control, and the currency grouping.
Design guidance
- Build one query per question. A query with 30 fields and 5 hidden filters is hard to maintain and slow to run.
- Put only the fields users need on rows and columns. Offer the rest as
#FREE. - Keep business logic in the cube or interface layer where more than one query needs it, and keep presentation choices (axes, display) in the query.
- Give each query a clear
@EndUserText.label. This is the name people see in the app finder and in report selection.
Exercise
A colleague builds a query on a cube and places NetAmount on #ROWS and CustomerId on #COLUMNS. The report shows one row for every distinct amount, and totals are missing. What is the cause, and what is the fix?
Show answer
A field on the rows axis is treated as a characteristic, so the result is grouped by each distinct value of NetAmount instead of aggregating it. Put NetAmount on #COLUMNS so the default aggregation (#SUM) applies, and put CustomerId on #ROWS so the amounts are grouped per customer.
Exercise
You need a column showing average net amount per unit. Should you compute it in the cube as net_amount / quantity or in the query? Give the reason.
Show answer
Compute it in the query. A ratio is not additive. If it is calculated per row in a lower view and then summed, totals are wrong. In the query, the engine aggregates numerator and denominator first and divides afterward, so each total is correct. Keep NetAmount and Quantity as additive measures in the cube.