是否有一种无需使用snocount
语句即可找到最大值SORT
的方法?
TYPES: BEGIN OF ls_student1,
snocount(5) TYPE n,
id TYPE i,
property(10) TYPE c,
value(10) TYPE c,
END OF ls_student1.
DATA: wa1 TYPE ls_student1,
lt_table4 TYPE HASHED TABLE OF ls_student1 with UNIQUE key snocount id.
lt_table4 = VALUE #(
( snocount = 1 id = 1 property = 'name' value = 'rambo' )
( snocount = 4 id = 1 property = 'age' value = '23' )
( snocount = 5 id = 1 property = 'college' value = 'VIL' )
( snocount = 3 id = 1 property = 'phone no' value = '9599993451' )
( snocount = 8 id = 1 property = 'f name' value = 'john whick' ) ).
LOOP AT lt_table4 INTO wa1.
WRITE:/ wa1-snocount, wa1-id, wa1-property, wa1-value.
ENDLOOP.
程序:
DATA row_with_max_snocount TYPE ls_student1.
LOOP AT lt_table4 INTO DATA(candidate).
IF candidate-snocount > row_with_max_snocount-snocount.
row_with_max_snocount = candidate.
ENDIF.
ENDLOOP.
功能表达式:
DATA(row_with_max_snocoun) =
REDUCE ls_student1(
INIT max = VALUE #( )
FOR row IN lt_table4
NEXT max = COND #(
WHEN row-snocount > max-snocount
THEN row
ELSE max ) ).
两者都采取c * n步骤查找最大值。如果您一次执行此操作,并且仅在最大程度上执行此操作,这在计算理论方面是最佳的。
排序表以查找最大值通常需要更长的时间,c * n * log n步骤。仅当您要按顺序访问多行时,才值得这样做。
如果您还需要最低限度,还有另一种算法可以在3/2 * c * n步骤中完成。
对于具有很多列或包含嵌套结构的表,请考虑使用引用TYPE REF TO ls_student1
而不是变量TYPE ls_student1
,因为它们避免了在主存储器中复制数据。
另一种可能性是通过SORTED
而不是SNOWCOUNT
将内部表定义为HASHED
:
lt_table4 TYPE SORTED TABLE OF ls_student1 with UNIQUE key snocount id.
因此,主键的最后一行将包含最高的SNOCOUNT
值:
DATA(row_with_max_snocount) = lt_table4[ lines( lt_table4 ) ].
如果要保留哈希键(例如,由于性能),则可以定义二级排序索引:
lt_table4 TYPE HASHED TABLE OF ls_student1 with UNIQUE key snocount id
WITH NON-UNIQUE SORTED KEY by_snocount COMPONENTS snocount.
因此,辅助键BY_SNOCOUNT
的最后一行将包含最高的SNOCOUNT
值:
DATA(row_with_max_snocount) = lt_table4[ KEY by_snocount INDEX lines( lt_table4 ) ].