LOOP AT ... GROUP BY,带有动态组密钥 [英] LOOP AT... GROUP BY with dynamic group key

查看:294
本文介绍了LOOP AT ... GROUP BY,带有动态组密钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过使用动态组参数对数据进行分组来进行循环.

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.

在这个简单的示例中,您可以在运行时动态地创建分组键,方法是使用诸如CONDSWITCH的内联表达式创建分组键:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆