把内表的行列转换,网上的例子很多,但是新人想看懂,几乎很难,所以总结下我是怎么完成的。
比如:你的内表如图:
你想让内表最后展示成这样:如图:
那么完成之后会是这样:
完成这个过程,得用到动态内表。看代码:
[plain] view plaincopy
- DATA:BEGIN OF itab8 OCCURS 0,
- bezei LIKE zchannel-bezei, "销售办事处
- zdate LIKE zchannel-zdate, "日期
- salesamount LIKE zchannel-salesamount, "总额
- END OF itab8.
先排序:
[plain] view plaincopy
- SORT itab8 BY bezei zdate DESCENDING.
要以日期作为列,得先取得唯一的日期。
[plain] view plaincopy
- DATA TDATE LIKE SY-DATUM OCCURS 0 WITH HEADER LINE.
- LOOP AT itab8.
- TDATE = ITAB8-ZDATE.
- COLLECT TDATE.
- ENDLOOP.
下面构建动态内表结构
[plain] view plaincopy
- 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 = 1.
- wa_str-inttype = 'CHAR'.
- wa_str-intlen = 20.
- APPEND wa_str TO it_str.
- CLEAR wa_str.
- wa_str-fieldname = 'SELFI'.
- wa_str-col_pos = 1.
- wa_str-inttype = 'CHAR'.
- wa_str-intlen = 20.
- 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 = 1.
- wa_str-inttype = 'CHAR'.
- wa_str-intlen = 20.
- 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(20).
- LOOP AT ITAB8.
- ASSIGN COMPONENT 'BEZEI' OF STRUCTURE <dyn_wa> TO <FS>. "<span style="color: rgb(128, 128, 128); font-family: 微软雅黑; font-size: 10pt;">分配结构里的销售办事处,用FS字段 指向它</span>
注sophy: 这里就是为什么要用到reference。如果直接用field symbol这里会报错说没有这个component。现在用reference,在前面执行到的时候有create data这里在运行时根据 like line of <kyn_table> 动态赋予了表结构。 - <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.