ABAP CDS 中的多个 SUM 聚合

Multiple SUM aggregates in ABAP CDS

我有 table 个不同状态的工单和多个工厂,如下所示:

植物 订单号 状态
工厂 1 订单 1 打开
工厂 1 订单 2 已发布
工厂 1 订单 3 完成
工厂 1 订单 4 打开
工厂 1 订单 5 已发布
工厂 1 订单 6 完成
植物 2 订单 7 已发布
植物 2 订单 8 完成

我想创建一个 CDS 来获取每个工厂的总数:“总订单”加上每个状态聚合的一列。预期结果如下:

植物 订单总数 打开 已发布 完成
工厂 1 6 2 2 2
植物 2 2 0 1 1

由于子查询是不可能的,我能想到的唯一解决方案是为每个聚合建立一个 CDS。 1 个用于植物总数,1 个用于每个植物状态。最后是具有预期结果的顶级 CDS。

但是对于应该相对简单的东西,这似乎有很多 CDS,因为实际上我有 7 个不同的状态,而不仅仅是 3 个。我的解决方案有更好的替代方案吗?

在字段列表中使用 CASE...WHEN...THEN...ELSE-expressionsStatus 转换为包含整数 0 或整数 1 的多列,具体取决于 Status 的值:

define view VIEWNAME as select from DATABASE_TABLE {
    key OrderId,
    Plant,
    CASE Status WHEN 'OPEN' THEN 1 ELSE 0 END AS Open,
    CASE Status WHEN 'RELEASED' THEN 1 ELSE 0 END AS Released,
    CASE Status WHEN 'COMPLETED' THEN 1 ELSE 0 END AS Completed
}

现在您可以创建一个 second 视图来查询此 first 视图。制作该视图 GROUP BY Plant。然后使用 COUNT( * ) 获取每个工厂的订单总数,并在 Open、Released 和 Completed 字段上使用 SUM 获取它们各自的计数:

define view VIEWNAME2 as select from VIEWNAME {
    key Plant,
    COUNT( * ) as TotalOrders,
    SUM( Open ) AS Open,
    SUM( Released ) AS Released,
    SUM( Completed ) AS Completed
}
GROUP BY Plant

另一种实现旋转的方法是使用 UNION,遵循我 用于 HANA CDS 的相同方法。这是 Philipp 使用的另一种方式。

合并状态总和的第一个视图:

define view ZORDERS (plant, TOTAL, OPENED, RELEASED, COMPLETED) as 
select from zplants {
    plant, count(distinct orderid ) as TOTAL, 0 as OPENED, 0 as RELEASED, 0 as COMPLETED
}  group by plant
union
select from zplants {
    plant, 0 as TOTAL, count(distinct orderid ) as OPENED, 0 as RELEASED, 0 as COMPLETED
} where status = 'OPENED' group by plant
union
select from zplants {
    plant, 0 as TOTAL, 0 as OPENED, count(distinct orderid ) as RELEASED, 0 as COMPLETED
} where status = 'RELEASED' group by plant
union
select from zplants {
    plant, 0 as TOTAL, 0 as OPENED, 0 as RELEASED, count(distinct orderid ) as COMPLETED
} where status = 'COMPLETED' group by plant

聚合它们的第二个视图:

define view ZPIVOT as select from ZORDERS {
    plant,
    sum ( TOTAL ) as TOTAL, 
    sum ( OPENED ) as OPENED, 
    sum ( RELEASED ) as RELEASED,
    sum ( COMPLETED ) as COMPLETED
} group by plant 

注意:这里我使用了OPENED,因为OPEN是ABAP CDS中的保留字。