LOOP AT... GROUP BY 使用动态组键 [英] LOOP AT... GROUP BY with dynamic group key
问题描述
我正在尝试通过使用动态组参数对数据进行分组来进行循环.
I am trying to loop by grouping data with dynamic group parameter.
我们可以在循环的 WHERE 条件上使用动态查询,但我不知道是否可以在组条件中使用动态字符串.
We can use dynamic queries on WHERE conditions on loops but I do not know whether it is possible to use a dynamic string in group condition.
以下是用户决定按哪个字段分组,然后根据决定添加其他逻辑的示例:
Here is the sample where user decides by which field to group and then put additional logic based on the decision:
DATA query TYPE string.
IF i_condition_type = 'ERNAM'.
query = |ERNAM = MARA-ERNAM|.
ELSE.
query = |ERSDA = MARA-ERSDA|.
ENDIF.
LOOP AT lt_mara INTO DATA(mara) GROUP BY ( (query) ) "syntax error
ASSIGNING FIELD-SYMBOL(<group>).
LOOP AT GROUP <group> ASSIGNING FIELD-SYMBOL(<line_data>).
"//do something
ENDLOOP.
ENDLOOP.
有没有办法做到这一点?除了分组,我也愿意接受其他想法,因为如果我不能动态分组,我会复制这么多行并只更改组键.
Is there any way to do this? I am also open to other ideas besides grouping because if I can't dynamically group, I will copy so many lines and change only the group key.
推荐答案
正如评论中所指出的,LOOP AT ... GROUP BY
不支持来自字符串的动态 group-by 子句.
As pointed out in the comments, LOOP AT ... GROUP BY
doesn't support dynamic group-by clauses from strings.
在这个简单的例子中,您可以在运行时动态创建分组键,方法是使用内联表达式(如 COND
或 SWITCH
)创建它:
In this simple example you could create your grouping key dynamically at runtime by creating it with an inline expression like COND
or SWITCH
:
LOOP AT lt_mara INTO DATA(mara) GROUP BY
SWITCH string(
i_condition_type
WHEN 'ERNAM' THEN mara-ernam
WHEN 'ERSDA' THEN mara-ersda
ELSE ''
)
但是您的密钥构建逻辑可能太复杂而无法用表达式(或至少是人类仍然可读的表达式)来表达.在这种情况下,您还可以执行其他操作:对方法返回的值进行分组:
But your key-building logic might be too complex to express with an expression (or at least an expression which is still readable by a human being). In that case there is something else you can do: group on values returned by a method:
LOOP AT lt_mara INTO DATA(mara)
GROUP BY my_grouping_method( line = mara
condition = i_condition_type )
然后该方法的实现可以包含您在运行时形成分组键所需的任何逻辑:
The implementation of that method can then include any logic you need to form the grouping key at runtime:
METHOD my_grouping_method.
IF condition = 'ERNAM'.
result = line-ernam.
ELSE.
result = line-ersda.
ENDIF.
ENDMETHOD.
分组方法也可以是不同对象的方法.因此,您可以将您的分组条件表示为一个自己的类.这将允许您编写这样的代码:
The grouping method can also be a method of a different object. So you could represent your grouping condition as an own class. That would allow you to write code like this:
DATA(lo_group_condition) = NEW zcl_mara_group_condition( 'ERNAM' ).
LOOP AT lt_mara INTO DATA(mara)
GROUP BY lo_group_condition->get_key_from( mara )
这篇关于LOOP AT... GROUP BY 使用动态组键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!