简单介绍几个CDS视图聚合函数
更多内容关注公众号:SAPtechnical
今天简单介绍几个CDS视图聚合函数。
1、SUM
代码举例如下:
@AbapCatalog.sqlViewName: 'ZCDS_AGGR'
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Aggregations'
define view Z_Cds_Agg_sum as select from snwd_stock
join snwd_pd on snwd_stock.product_guid = snwd_pd.node_key
{
key snwd_pd.product_id,
snwd_pd.category,
// Aggregate function "SUM"
sum(snwd_stock.quantity) as total_stock
}
group by snwd_pd.category,
snwd_pd.product_id
在上面的示例中,ABAP CDS视图使用聚合函数SUM和GROUP BY product和category来取出产品的总库存。
2、MAX
代码举例如下:
@AbapCatalog.sqlViewName: 'ZCDS_AGGR'
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Aggregations'
define view Z_Cds_Agg_max as select from snwd_so
join snwd_bpa on snwd_so.buyer_guid = snwd_bpa.node_key
{
key snwd_bpa.bp_id,
snwd_bpa.company_name,
// Aggregate function "MAX"
max(snwd_so.gross_amount) as max_sales_amt
} group by snwd_bpa.bp_id,
snwd_bpa.company_name
在上面的示例中,ABAP CDS视图使用聚合函数MAX和GROUP BY bp_id和company_name取出客户产生的最大销售额。
3、MIN
代码举例如下:
@AbapCatalog.sqlViewName: 'ZCDS_AGGR'
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Aggregations'
define view Z_Cds_Agg_min as select from snwd_so
join snwd_bpa on snwd_so.buyer_guid = snwd_bpa.node_key
{
key snwd_bpa.bp_id,
snwd_bpa.company_name,
// Aggregate function "MIN"
min(snwd_so.gross_amount) as min_sales_amt
} group by snwd_bpa.bp_id,
snwd_bpa.company_name
在上面的示例中,ABAP CDS视图使用聚合函数MIN和GROUP BY bp_id和company_name取出客户产生的最小销售额。
4、COUNT(*)
代码举例如下:
@AbapCatalog.sqlViewName: 'ZCDS_AGGR2'
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Aggregations'
define view Z_Cds_Agg as select from snwd_so
join snwd_bpa on snwd_so.buyer_guid = snwd_bpa.node_key
{
key snwd_bpa.bp_id,
snwd_bpa.company_name,
// Aggregate expression COUNT( * )
count(*) as min_sales_amt
} group by snwd_bpa.bp_id,
snwd_bpa.company_name
在上面的示例中,ABAP CDS视图使用聚合函数COUNT(*)和GROUP BY bp_id和company_name取出为业务伙伴创建的销售订单总数。
5、COUNT(DISTINCT)
代码举例如下:
@AbapCatalog.sqlViewName: 'ZCDS_AGGR_4'
@AbapCatalog.compiler.compareFilter: true
@AccessControl.authorizationCheck: #CHECK
@EndUserText.label: 'Aggregate Expressions'
define view Zcds_Agg_C as select from snwd_so_i
join snwd_pd on snwd_so_i.product_guid = snwd_pd.node_key
{
key snwd_pd.product_id,
// Aggregate Expression - COUNT( DISTINCT )
count( distinct snwd_so_i.node_key) as orders_count
} group by snwd_pd.product_id
在上面的示例中,ABAP CDS视图使用聚合函数COUNT(DISTINCT)和GROUP BY product_id取出针对产品创建的销售订单总数。
总结:
①:使用的每个聚合表达式都需要使用AS定义替代元素名称。
②:聚合表达式应该需要GROUP BY子句。
③:CDS视图中使用的所有非聚合字段都应在GROUP BY子句中指定。