sap中COLLECT的用法
时间: 2023-07-08 09:06:32 浏览: 196
SAP ABAP应用程序中"锁"的介绍
在SAP ABAP中,COLLECT是一个用于聚合相同记录的语句。它将相同的行合并为一个,并将非关键字段的值相加。
COLLECT语句的基本语法如下:
```
COLLECT <itab> INTO <wa> [WITH <key>]
```
其中,`<itab>`是输入内表,`<wa>`是输出工作区,`<key>`是可选的关键字,指定要聚合的字段。
以下是一些使用COLLECT语句的示例:
1. 将相同的销售订单行项目合并为一个,并将数量相加:
```
TYPES: BEGIN OF ty_sales,
orderid TYPE vbak-vbeln,
item TYPE vbap-posnr,
qty TYPE vbap-erfmg,
END OF ty_sales.
DATA: lt_sales TYPE TABLE OF ty_sales,
ls_sales TYPE ty_sales,
lt_result TYPE TABLE OF ty_sales.
SELECT vbeln posnr erfmg
FROM vbap
INTO CORRESPONDING FIELDS OF TABLE lt_sales.
LOOP AT lt_sales INTO ls_sales.
COLLECT ls_sales INTO ls_sales GROUP BY ( orderid = ls_sales-orderid item = ls_sales-item ) WITH SUMMATION qty.
ENDLOOP.
SORT lt_sales BY orderid item.
APPEND LINES OF lt_sales TO lt_result.
```
2. 将相同的部门名称合并为一个,并计算员工数量和平均工资:
```
TYPES: BEGIN OF ty_employee,
name TYPE string,
dept TYPE string,
salary TYPE p,
hiredate TYPE d,
END OF ty_employee.
DATA: lt_employee TYPE TABLE OF ty_employee,
ls_employee TYPE ty_employee,
lt_result TYPE TABLE OF ty_employee.
SELECT name dept salary hiredate
FROM employee
INTO CORRESPONDING FIELDS OF TABLE lt_employee.
LOOP AT lt_employee INTO ls_employee.
COLLECT ls_employee INTO ls_employee GROUP BY dept WITH SUMMATION salary AND COUNT name.
ENDLOOP.
SORT lt_employee BY dept.
APPEND LINES OF lt_employee TO lt_result.
```
在这些示例中,我们使用COLLECT语句将相同的记录合并为一个,并计算非关键字段的总和或平均值。
阅读全文