把内表的行列转换,网上的例子很多,但是新人想看懂,几乎很难,所以总结下我是怎么完成的。
比如:你的内表如图:
你想让内表最后展示成这样:如图:
那么完成之后会是这样:
完成这个过程,得用到动态内表。看代码:
DATA:BEGIN OF itab8 OCCURS ,
bezei LIKE zchannel-bezei, "销售办事处
zdate LIKE zchannel-zdate, "日期
salesamount LIKE zchannel-salesamount, "总额
END OF itab8.
先排序:
SORT itab8 BY bezei zdate DESCENDING.
要以日期作为列,得先取得唯一的日期。
DATA TDATE LIKE SY-DATUM OCCURS WITH HEADER LINE.
LOOP AT itab8.
TDATE = ITAB8-ZDATE.
COLLECT TDATE.
ENDLOOP.
下面构建动态内表结构
DATA: dy_table TYPE REF TO data,
dy_wa TYPE REF TO data,
it_str TYPE lvc_t_fcat, "是Table Type
wa_str TYPE lvc_s_fcat. "是一个Structure 用于存储即将构建的动态内表结构 FIELD-SYMBOLS: <dyn_table> TYPE table, "是一个标志,可以理解为一个指针,将来创建的内表就要通过它们来访问
<dyn_wa> TYPE ANY,
<FS> TYPE ANY. wa_str-fieldname = 'BEZEI'.
wa_str-col_pos = .
wa_str-inttype = 'CHAR'.
wa_str-intlen = .
APPEND wa_str TO it_str.
CLEAR wa_str. wa_str-fieldname = 'SELFI'.
wa_str-col_pos = .
wa_str-inttype = 'CHAR'.
wa_str-intlen = .
APPEND wa_str TO it_str.
CLEAR wa_str. REFRESH fieldcat.
PERFORM input_fieldcat USING 'BEZEI' '销售办事处' '' '' '' '' ''. LOOP AT TDATE.
wa_str-fieldname = TDATE.
wa_str-col_pos = .
wa_str-inttype = 'CHAR'.
wa_str-intlen = .
APPEND wa_str TO it_str.
CLEAR wa_str.
PERFORM input_fieldcat USING TDATE TDATE '' '' '' '' ''.
ENDLOOP. *此方法用于构建动态内表,输入=构建的结构,输出=dy_table
CALL METHOD cl_alv_table_create=>create_dynamic_table
EXPORTING
it_fieldcatalog = it_str
IMPORTING
ep_table = dy_table. ASSIGN dy_table->* TO <dyn_table>.
CREATE DATA dy_wa LIKE LINE OF <dyn_table>.
ASSIGN dy_wa->* TO <dyn_wa>.
下面往结构里写数
DATA FIELDNAME().
LOOP AT ITAB8.
ASSIGN COMPONENT 'BEZEI' OF STRUCTURE <dyn_wa> TO <FS>. "分配结构里的销售办事处,用FS字段 指向它
<FS> = ITAB8-BEZEI.
FIELDNAME = ITAB8-ZDATE. "这里把日期类型定义为char型,因为用DATS报错。
ASSIGN COMPONENT FIELDNAME OF STRUCTURE <dyn_wa> TO <FS>. "分配结构的日期,将FS指向它
<FS> = ITAB8-SALESAMOUNT.
AT END OF BEZEI.
APPEND <dyn_wa> TO <dyn_table>.
ENDAT.
ENDLOOP.