我有一张具有不同状态和多个工厂的工单表,如下所示:
植物 | 订单ID | 状态 |
---|---|---|
植物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 表达式 将
Status
转换为多个列,其中包含整数 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 描述的相同方法。 这是菲利普使用方式的另一种风格。
联合状态总和的第一个视图:
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 中的保留字。
您可以通过使用自连接来使用一个 CDS 来完成此操作,如示例所示:
define view VIEWNAME as select from DB_TAB
left outer join DB_TAB as DB_TAB1 on DB_TAB.Plant = DB_TAB1.Plant
and DB_TAB.OrderID = DB_TAB1.OrderID
and DB_TAB1.Status = 'OPEN'
left outer join DB_TAB as DB_TAB2 on DB_TAB.Plant = DB_TAB2.Plant
and DB_TAB.OrderID = DB_TAB2.OrderID
and DB_TAB2.Status = 'RELEASED'
left outer join DB_TAB as DB_TAB3 on DB_TAB.Plant = DB_TAB3.Plant
and DB_TAB.OrderID = DB_TAB3.OrderID
and DB_TAB3.Status = 'COMPLETED'
{
key Plant,
count( * ) as Total_Orders,
count( distinct DB_TAB1.OrderID ) as Open,
count( distinct DB_TAB2.OrderID ) as Released,
count( distinct DB_TAB3.OrderID ) as Completed,
}
group by Plant