本文主要介绍SAP ABAP中OPEN SQL的GROUPING和SORT语句
AGGREGATE函数分类
函数 | 功能 |
AVG | 取平均值 |
COUNT | 取个数 |
MAX | 取最大值 |
MIN | 取最小值 |
STDDEV | 取标准偏差 |
SUM | 取合计 |
注意!所有AGG函数的括号内字段前后必须有一个空格如SUM( CARRID ),否则系统检测不出来!
GROUP BY
使用Aggregate函数之前,选择数据时需要用GROUP BY语句进行分组。GROUP BY语句是当表的特定字段中存在相同的值时就显示在一行中
SELECT <f1> <f2> <agg>... GROUP BY <f1> <f2>
案例代码演示
DATA:GV_CARRID TYPE SFLIGHT-CARRID, GV_PRICE TYPE I. SELECT CARRID SUM( PRICE ) INTO (GV_CARRID,GV_PRICE) FROM SFLIGHT GROUP BY CARRID. WRITE:/ GV_CARRID,GV_PRICE. ENDSELECT.
效果示例图
HAVING
HAVING语句主要是用来对进行分组后进行限制条件的语句,要放在GROUP BY语句之后,下面案例演示中限制了上面SUM( PRICE )的值需要大于1000
SELECT <f1> <f2> <agg>... ... GROUP BY <f1> <f2> HAVING <condition>
案例代码演示
DATA:GV_CARRID TYPE SFLIGHT-CARRID, GV_PRICE TYPE I. SELECT CARRID SUM( PRICE ) INTO (GV_CARRID,GV_PRICE) FROM SFLIGHT GROUP BY CARRID HAVING SUM( PRICE ) > 1000. WRITE:/ GV_CARRID,GV_PRICE. ENDSELECT.
效果示例图
SORT
在查询数据时可以使用ORDER BY语句,则查询出来的结果会按照ORDER BY指定的字段进行排序。若不使用ORDER BY就会任意地显示排序结果。其中ORDER BY语句还有如下特点需要牢记
- 根据表地KEY值进行排序
- 只适用于SELECT*语句
- 在JOIN语句和视图中无法使用
- 若不指定排序为升序还是降序则默认为升序
SELECT <lines>* ... ORDER BY <f1>[ASCENDING|DESCENDING] <f2>[ASCENDING|DESCENDING]....
案例代码演示(CARRID升序)
DATA:GV_CARRID TYPE SFLIGHT-CARRID, GV_PRICE TYPE I. SELECT CARRID SUM( PRICE ) INTO (GV_CARRID,GV_PRICE) FROM SFLIGHT GROUP BY CARRID HAVING SUM( PRICE ) > 1000 ORDER BY CARRID ASCENDING. WRITE:/ GV_CARRID,GV_PRICE. ENDSELECT.
效果示例图
案例代码演示(CARRID降序)
DATA:GV_CARRID TYPE SFLIGHT-CARRID, GV_PRICE TYPE I. SELECT CARRID SUM( PRICE ) INTO (GV_CARRID,GV_PRICE) FROM SFLIGHT GROUP BY CARRID HAVING SUM( PRICE ) > 1000 ORDER BY CARRID DESCENDING. WRITE:/ GV_CARRID,GV_PRICE. ENDSELECT.
效果示例图