SAP CDS View語法進階(聚集、JOIN、UNION)

在上一篇博客《SAP CDS View基礎語法(創建你的第一個CDS View)》
中,我介紹了CDS View的基礎語法。在本篇博客中,我將介紹一些CDS運算的進階用法,包括聚集、JOIN和UNION三個部分。

1 聚集

用途:

完成聚集運算,例如MIN,MAX,COUNT,SUM等

語法:

@AbapCatalog.sqlViewName: 'ZDEMO_CDS_SQL'
@AbapCatalog.preserveKey: true
define view ZDEMO_CDS_DDL
  as select from sflight
{
  planetype,
  min(price) as min_price,
  max(price) as max_price,
  sum(price) as sum_price,
  count(*)   as count_planes

}
group by
  planetype

解釋:

  • 使用聚集運算時,要使用group by指定聚集的件,也即按哪些字段進行分組統計。

運行效果:
在這裏插入圖片描述

2 聚集運算中的Having語句

用途:

指定聚集運算過程中的篩選條件

語法:

@AbapCatalog.sqlViewName: 'ZDEMO_CDS_SQL'
@AbapCatalog.preserveKey: true
define view ZDEMO_CDS_DDL
  as select from sflight
{
  planetype,
  min(price) as min_price,
  max(price) as max_price,
  sum(price) as sum_price,
  count(*)   as count_planes

}
group by
  planetype
having
  planetype = '747-400'
  or count(*)  > 60

解釋:

  • Having中指定的條件字段,只能是group by中的字段的子集;在Having中也可以使用聚集運算的中間結果集作爲刪選條件

運行效果:
在這裏插入圖片描述

3 JOIN

用途:
CDS支持Inner Join, Left Outer Join,Right Outer Join
語法:

@AbapCatalog.sqlViewName: 'ZDEMO_CDS_SQL'
@AbapCatalog.preserveKey: true
define view ZDEMO_CDS_DDL
  as select from sbook   as a
    inner join   sflight as b on  a.carrid = b.carrid
                              and a.connid = b.connid
                              and a.fldate = b.fldate
{
  a.carrid    as airline_code,
  a.connid    as connection_number,
  a.fldate    as flight_date,
  a.customid  as customer_id,
  b.planetype as planetype
}
where
  a.carrid = 'DL'

解釋:

  • Inner Join, Left Outer Join, Right Outer Join的用法同ABAP OPEN SQL的用法一致

運行效果:
在這裏插入圖片描述

4 UNION

用途:
UNION兩個SELECT的結果集

語法:

@AbapCatalog.sqlViewName: 'ZDEMO_CDS_SQL'
@AbapCatalog.preserveKey: true
define view ZDEMO_CDS_DDL
  as select distinct from sbook
{
  carrid as airline_code,
  connid as connection_number,
  fldate as flight_date
}
where
  carrid = 'DL'

union

select distinct from sflight
{
  carrid as airline_code,
  connid as connection_number,
  fldate as flight_date
}
where
  planetype = '747-400'

解釋:

  • UNION可以合併兩個SELECT的結果集,並自定去除重複的條目
  • UNION ALL 合併結果集,保留重複的條目
  • 合併的兩個結果集要有相同字段數
  • 合併結果集的列類型要兼容
  • 字段名稱要相同

運行效果:
在這裏插入圖片描述

5 小結

在本文中,我們進一步介紹了SAP CDS View的運算語法,相信通過這兩篇博客,各位同學應該已經學會了創建CDS View,以及用CDS View完成運算邏輯。CDS View還有很多其他的用法,感興趣的同學,可查看ABAP 的幫助文檔。

高質量的SAP技術博客,歡迎關注❤️、點贊👍、轉發📣!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章