Detailed explanation of ABAP OPEN SQL

Contents of this chapter

  1. overview
  2. OPEN SQL – read data

1 Overview

1.1 R/3 architecture

Learn about the R/3 architecture before learning SQL. As shown in [Figure 1], SAP R/3 is divided into three layers.
Among them, the application layer and the database layer are composed of separate systems.
1. Presentation Layer
Presentation Layer (Presentation Layer) simply refers to a personal PC, which is a machine that stores software components (Software Component) that constitute SAPGUI (Graphical User Interface). Provide the interface between R/3 system and users at this level. SAP GUI refers to a terminal device installed on a personal PC through which users input or query data.

  1. application layer

All SAP programs are executed on the application layer (ApplicationLayer), and the SAP GUI only plays a terminal role.
figure 1
The application layer of the operation server consists of one or more application servers and a document server (Message Server).
The document server and the application server are connected to each other, so that the user automatically selects a small server to log in. Among them, multiple application servers can be used to distribute the load of the system. There is a local buffer on the application layer in SAP. If the buffer is set on the database table in the ABAP data dictionary, the data will be read directly in the local buffer without accessing the database layer.
This setting can improve SAP performance, but only for OPEN SQL. The Dispatcher is used to properly distribute the Work Process.
3. Database layer
The database layer (Database Layer) is closely related to the SQL statements to be learned in this chapter. All data in SAP are stored in this layer, that is, the database stores master data, transaction codes and all data of the R/3 system. For example, it stores system variables representing the execution environment of the R/3 system, codes of all programs and transaction code data, etc.
An ABAP program consists of items such as codes, screens, functions, and database tables, which are stored in R/3 storage, and users manage (create/modify/query) these objects in the ABAP workspace. As shown in [Figure 2], the application layer and database layer of most programming languages ​​such as JAVA, ASP, and JSP are separated from each other. On the application layer, create a GUI for the interaction between the user and the screen (Dialog), which is mainly responsible for querying/maintaining the data of the database layer.
In the database layer, database objects such as database tables/views/structures can be created and managed through the DBMS. In this environment, developers modify data through the GUI screen of the application or connect directly to the database to execute SQL.
figure 2
SAP prohibits ordinary users from directly connecting to the database to modify data, and sometimes even restricts the authority to query data. This setting is to ensure data integrity, consistency, security and transparency. Of course, if the system information, ID and password of the database are made public, the channel of direct access to the database cannot be completely cut off. As shown in [Figure 3], the ABAP developer manages the database structure through the ABAP data dictionary.
image 3

1.2 SQL definition

SQL is Structured Query Languagean acronym for SQL and is a standard language often used in relational databases.
It is divided into the following three types. Among these three types, only the DML language is allowed in the OPEN SQL of the ABAP program.

  • Data Manipulation Language (DML): language for processing data

- is a language for querying, inserting, deleting, updating database data.

  • Data Definition Language (DDL): A language for defining data

-It is the interface for transferring data between the application program and the database management system, and is generally used to create a database.

  • Data Control Language (DCL): language for controlling data

-It is a language used to ensure data integrity, security, access control, and recovery, and is generally used to protect data.

1.3 Types of SQL

SQL language includes OPEN SQL and NATIVESQL.
OPEN SQL can only be used in ABAP language, and can be connected to the database after being parsed into NATIVE SQL through the database interface. So the SQL language used in the database is NATIVE SQL.

1.4 OPEN SQL与NATIVE SQL

The SQL flow controller of the application program-database server is shown in Figure 4.
Figure 4

  1. OPEN SQL

OPEN SQL is composed of ABAP commands to create database data, and its syntax is the same in different DBMS (database management system) environments. OPEN SQL cannot use DDL, DCL, and can only use SELECTDML language similar to statements. In addition, local buffers can also be used, and it is easier to use than NATIVE SQL.
The ABAP program has the feature of automatically executing Syntax Check when it is activated.

  1. NATIVE SQL

NATIVE SQL language can be directly connected to the database using DML, DDL language.
DDL language can directly create/modify database tables. Command statements ( SELECT, UPDATE, DELETEetc.) of OPEN SQL can also be used, and problems that cannot be solved with OPEN SQL can be solved with NATIVE SQL.

1.5 SQL and local buffers

SAP local buffer is a technology supported by R/3 architecture, which is mainly responsible for reducing database load. But you have to set the use of buffers in the technical settings of the database table. For the setting method of the buffer, please refer to "Chapter 7 ABAP Data Dictionary".

SELECT * FROM marc WHERE werks='1101'
IF SY-SUBRC EQ 0.
WRITE marc.
EXIT.
ENDIF.
ENDSELECT.

The running sequence of the SQL statement shown above is shown in [Figure 5].
Figure 5
The following analyzes the SQL execution sequence shown in [Figure 3-5]. ① Execute the SQL statement to query data
from the database table MARC . ② The OPEN SQL at the database interface is parsed into NATIVE SQL, and then the data whose WERKS field value is '1101' is queried from the database table MARC. ③ There are 3 pieces of data in the database table MARC, and these 3 pieces of data are stored in the local buffer. SQL statement . It refers to the successful execution of the statement to obtain data from the database, and then execute the EXIT statement to jump out of the F statement and display the first data whose value is '1101'. When re-executing the SQL statement, due to the existing data in the local buffer, the data can be obtained directly in the local buffer without accessing the database again.WERKS='1101'

WERKS='1101'SY-SUBRC EQ '0'
WERKS = '1101'

1.6 Overview of OPEN SQL

OPEN SQL is the language used by the R/3 system, and has the function of querying/modifying database data. It has nothing to do with the database system used (Oracle, MSSQL, Max DB, etc.), and the SQL execution results are the same. It is applicable to the database tables and views created in the ABAP data dictionary, and can only perform the functions restricted in the Cluster and Pooled database tables to be learned in Chapter 7. OPEN SQL generally depends on the client (Client).
In [Figure 6] it can be seen that the R/3 system is composed of multiple independent customers (such as individual legal persons belonging to a group). The database table is an object that depends on the client-independent existence (Client-independent), so even if the database table is created in 100 clients, it also exists in 200 and 300 clients, but the data generated in the database table of 100 clients only
exists customers. If the MANDT field does not exist in the ABAP data table, the database table data has attributes that depend on the customer. If the MANDT field does not exist in the table, the table has the Client-independent attribute. As shown in [Figure 3-6], the actual database tables store customer information in the field MANDT.
Figure 6
Frequently used commands in OPEN SQL are shown in [Table 1]. All OPEN SQL executions will return the system variable SY-SUBRCas 0 (if it fails, it will return a value other than 0), and the system variable SY-DBCNTwill return the number of data.

Guan Jian character Function
SELECT Read data from database table
INSERT UPDATE Append data to the database table Modify the data of the database table
MODIFY Execute the INSERT+UPDATE function UPDATE: when the data already exists in the database table (distinguish whether it exists by key value) INSERT: when the data does not exist in the database table (distinguish whether it exists by key value)
DELETE Delete database table data

Table 1 OPEN SQL command statement

2 OPEN SQL - read data

The statement to read data from the database table is shown in [Table 2]. First learn the function definition of each sentence, and then master its specific usage through practice.

sentence Function
SELECT The SELECT statement can list the database table fields and read one or more pieces of data
INTO The INTO statement is used to specify the variable where the queried data is stored, and then use this variable in the program
FROM The FROM statement is used to specify the database table to be queried. Can be written before and after the INTO statement
WHERE You can limit the conditions to query data
GROUP BY Used to query data by group. For example, the GROUP BY statement is often used when grouping and summing
HAVING HAVING is a statement used to restrict GROUP BY conditions.
ORDER BY A WHERE statement similar to SELECT is used to sort (sort) the data queried

Table 2

2.1 SELECT statement

SELECTstatement to read the necessary data from the database table.

  1. **SELECT**

The SELECT statement is divided into two parts. Part of it is used to specify the number of pieces of query data, and a statement is used when querying one piece SINGLE. The other part is < columns>, which is used to specify the database table field to be queried.

SELECT …

  1. a piece of data

Statements are used when fetching a piece of data from the database SINGLE. Using this statement will only get one piece of data, so the conditions for querying data must be given correctly. That is, WHEREadd all values ​​to the condition key. When not all keyvalues ​​are specified, any one of the multiple items will be returned, which will cause the read data to be different from the expected result. Use * when reading all fields of a database table.

SELECT SINGLE …WHERE

  1. Several Line

When multiple pieces of data are obtained, SELECTthe result will be saved to the internally defined table. This kind of table ABAPis called internal table (Internal Table) in the language. The internal table will be described in detail in Chapter 5 (the internal table is a virtual table for storing data generated in ABAP memory). DISTINCTstatement to remove duplicate values.

SELECT [DISTINCT] …WHERE

INTOWhen the result of the statement is not saved to the internal table, but to a field or structure (Work Area...), ENDSELECTthe statement must be added at the end. This kind of statement is equivalent to LOOPexecuting SELECTa statement in a loop. Every time a piece of data is taken out, it is appended to the structure until all qualified data is read.

SELECT[DISTINCT] … WHERE …
ENDSELECT.

REPORT Z0_01.

DATA:gt_itab TYPE STANDARD TABLE OF sflight,
gs_wa TYPE sflight.
SELECT * INTO gs_wa FROM sflight
WHERE carrid EQ 'LA'".
WRITE: / gs_wa-carrid,
gs_wa-connid.
ENDSELECT.


DATA: gt_itab TYPE STANDARD TABLE OF sflight,
gs_wa TYPE sflight.
SELECT * INTO TABLE gt_itabFROM sflight
WHERE carrid EQ 'AA'.
LOOP AT gt_itab INTO gs_wa.
WRITE: / gs_wa-carrid,
gs_wa-connid.
ENDLOOP.

  1. AS (alias)

The AS statement can be used to specify an alias for a field.

SELECT[AS]…

  1. dynamic **SELECT**statement

The fields of a statement can be defined dynamically SELECT. A structure holding a dynamic statement GS_LINEcan hold up to a 72-bit CHARtype. When the structure GS_LINEis , nullit is the same as the * statement.

SELECT () …

REPORT z0_02.
DATA:gt_itab TYPE STANDARD TABLE OF sflight,gs_wa LIKE LINE OF gt_itab.
DATA:gs_line(72) TYPE c,
gt_list LIKE TABLE OF gs line(72).
gs_line = 'CARRID CONNID'.
SELECT DISTINCT (gs_line) INTO TABLE gt_itabFROM sflight.
IF sy-subrc EQ 0.
LOOP AT gt_itab INTO gs_wa.
WRITE: / gs_wa-carrid, gs_wa-connid.
ENDLOOP.
ENDIF.

gt_itabIt is an internal table that holds SELECTstatement result values.
gs_lineIt is a 72-bit CHAR type. gs_lineWrite the field name in the variable, and output SFLIGHTthe field value of the query table carrid connidto the screen. If you need more than 72 bits, you can define the internal table of the 72-bit internal table and use it. For details, please refer to [Example 3].

REPORT z0_03.-----中间省略---
DATA gs_line(72) TYPE c.
DATA gt_list LIKE TABLE OF gs_line(72).
gs_line = 'CARRID CONNID'.
APPEND gs_line TO gt_list.
SELECT DISTINCT (gt_list) INTO TABLE gt_itabFROM sflight.
-----中间省略-----

2.2 INTO statement

Use this statement to specify the destination for storing the result values ​​of the SELECT statement query.

  1. structure

When querying a piece of data, use a structure (Work Area, variable, structure), and use an asterisk * to get the values ​​of all fields. At this time, using CORRESPONDING FIELDS OFthe statement will automatically find the matching assignment of the same field name.

SELECT … INTO [CORRESPONDING FIELDS OF]。

  1. Internal Table

Use internal tables when querying multiple pieces of data. It is used when inserting data into the internal table APPENDING. It cannot be used INTO. INTOIt is used when inserting data after deleting the internal table data.

SELECT …INTO|APPENDING [CORRESPONDING FIELDS OF]
TABLE
[PACKAGE SIZE]…

PACKAGE SIZEThe number of pieces of data added to the inner table can be specified each time by using a statement. When PACKAGE SIZEit is set to 5, only 5 pieces of data are read and added to the internal table at a time. At this time, it should be noted that a ENDSELECTstatement is required.

REPORT z0_04.
DATA:gs _wa TYPE sflight,
gt_itab TYPE TABLE OF sflight.
SELECT carrid connid
FROM spfli
INTO CORRESPONDING FIELDS OF TABLE gt_itab PACKAGE SIZE 5.
LOOP AT gt_itab INTO gs_wa.
WRITE:/ gs_wa-carrid, gs_wa-connid.
ENDLOOP.
ENDSELECT.

Since PACKAGE SIZEit is specified as 5, SELECTthe statement only reads 5 values ​​each time and executes LOOPthe loop before re-executing SELECTthe statement. The inner table in [Example 3-4] gt_itabrefers to the database table sflight, and FROMthe statement refers to the database table spfli. These two tables are two different structures, so CORRESPONDING FIELDS OFthe option is used to make the two tables find the same field for assignment.

  1. Single Field

Use the following statement when querying individual fields of a database table or using the Aggregate function.
When more than two destinations are listed after the INTO statement, the variable names must be specified in parentheses. If there are blanks, a syntax error occurs.

SELECT … INTO (f1.f2… …)

The statement to query two fields in the SELECT statement is as follows.

SELECT carrid connid INTO (gv_carrid, gv_connid) FROM SFLIGHT.

2.3 FROM statement

Use FROMa statement to specify the corresponding database table (or view) to query data. FROMAfter the statement, you can specify a database table or a connection to multiple database tables. Not only can you add an alias using the AS statement, but you can also dynamically define the database table name.
FROMThe statement has two options, one that defines the table, and one that controls access to the database table.
Use FROMthe statement to specify the corresponding database table (or view) for the data to be queried. FROMAfter the statement, you can specify a database table or a connection to multiple database tables. Not only can you add an alias using the AS statement, but you can also dynamically define the database table name. FROMThe statement has two options, one that defines the table, and one that controls access to the database table.

SELECT … FROM table option .

The option syntax for controlling access to database tables in the FROM statement is shown in Table 3-3.
Table 3-3 Options for the FROM statement

sentence illustrate
CLIENT SPECIFIED Disable automatic client settings
BYPASSING BUFFER Data will not be read from SAP local buffers. Even if Buffering is set in the database table, it will directly access the database to read data
UP TO n ROws Limit the number of query data. Problems that degrade database performance due to user usage problems can be prevented. For example, when querying a large amount of data due to no date specified in the selection criteria
  1. select static table

Static tables can be defined to query data. Aliases can be used at this time, but the table name cannot be used in the SELECT statement.

SELECT … FROM [AS]

  1. select dynamic table

You can define dynamic tables to query data. At this time, the table name must be specified in uppercase letters and must be a name that exists in the ABAP data dictionary.

SELECT … FROM (dbtab).

The statement of querying data from the database table entered by the user on the screen is shown in [Example 5].

REPORT Z0_05.
PARAMETERS p_tname TYPE char10.DATA GS_WA TYPE SFLIGHT.
SELECT SINGLE* INTO gs_waFROM (p_tname)
WHERE carrid ='AA'.

Executing [Example 3-5] will display the selection screen shown in [Result 3-5]. On this screen, the user can input the name of the database table to query data, and the screen will be automatically generated by using a statement PARAMETERS. On this screen, SFLIGHTafter entering the name of the database table and clicking the execute button, FROM(p_tname)the variable used in the statement p_tnamewill be dynamically assigned the name of the database table entered by the user SFLIGHT.

  1. **JOIN**sentence

Use the JOIN statement to connect tables when obtaining multiple database table values ​​at the same time in a relational database. Generally use Primary Key(replaced by the abbreviation PK hereafter) and Foreign Key(replaced by the abbreviation FK hereafter) to connect database tables, but occasionally connect with logically related values, and use the ON statement to specify the connection conditions of the two tables.

SELECT …FROM [INNER] JOIN [AS ]
ON …

[Example 6] is INNER JOINan example of a statement. It can be found that the airline name does not exist in the database table storing aviation information SFLIGHT, but SCARRthe airline name corresponding to the airline ID exists in the database table. Therefore, JOINthe name of the airline can be read by joining the two tables with a statement.
If no type is specified when using JOINthe statement JOIN, it defaults to yes INNER JOIN.

REPORT z0_06.
TYPES: BEGIN OF t_str,
carrid TYPE sflight-carrid,carrname TYPE scarr-carrname,END OF t_str.
DATA: gs_str TYPE t_str.
SELECT SINGLE a~carrid b~carrname
INTO CORRESPONDING FIELDS OF gs_strFROM sflight AS a
INNER JOIN scarr AS bON a-carrid EQ b-carridWHERE a~carrid ='AA'.
WRITE : gs_str-carrid, gs_str-carrname.

[Result 3-6]
AA American Airlines

The AS statement in the JOIN statement in [Example 3-6] is used to specify an alias, that is, a in the sflight AS a statement is used as the database table sflight alias. Using an alias can simplify the program code, as can be seen from [Example 3-6], the sflight-carrid statement can be replaced by the a~carrid statement.

  1. I**NNER JOIN**and**OUTERJOIN**

There are two types of database table connection INNER JOINand . OUTER JOINThe methods in it OUTER JOINare as follows.

SELECT…FROMLEFT [OUTER] JOIN
[AS ]
ON

Assume that there are two personnel information database tables as shown in [Fig. 7]. The database table INSA stores the basic information of the employees, and the database table CERT stores the certificate information obtained by the employees. Employees ZHOU and KIM have certificates, but employee ZHONG does not. When executing INNER JON based on the employee number field, the employee ZHONG should be excluded from the query object.
Figure 7
It is assumed to be used when displaying basic information of all employees and additionally displaying certificate information OUTER JOIN. ABAP OPEN SQLCan only be used in LEFT OUTER JOIN. This statement uses the table on the left as the reference table to read data. The connection result is shown in Figure 3-8.
Figure 8
[Example 7] illustrates OUTER JOINthe method. Assume that the names of all airlines in the database table SCARRdo not exist, so airlines need LEFT OUTER JOINdatabase tables SFLIGHTand database tables in order to avoid missing the airline's aircraft information SCARR.

REPORT Z0_07.
TYPES: 
BEGIN OF t_str,
carrid TYPE sflight-carrid,
carrname TYPE scarr-carrname,
END OF t_str.
DATA: gs_str TYPE t_str.
SELECT SINGLE a~carrid b~carrname
INTO CORRESPONDING FIELDS OF gs_str FROM sflight AS a 
LEFT OUTER JOIN scarr AS b ON a~carrid EQ b~carrid
WHERE a~carrid = 'AA'.
WRITE: gs str-carrid, gs str-carrname.


  1. Limit the number of queries

Use the following statements to limit the number of data to be queried.

SELECT …FROM UP TO ROWs…

SELECTIOIN SCREENThis statement is equivalent to the maximum acquisition number in the program query condition of [Fig. 3-9] . When the user directly executes the program without inputting query conditions, all the values ​​in the database table will be queried, which will increase the system load. At this time, you can specify the maximum number of acquisitions to limit the number of acquired data.

2.4 WHERE statement

WHEREStatements can specify query conditions to enable users to correctly obtain the data they need. This statement is also applicable to commands such as UPDATE, and so on.DELETE

  1. WHERE conditional statement

SELECT …WHERE …

[Table 4] describes the types of operators used in the WHERE statement.
image.png

  1. Interval conditions

Use this statement when you need to append range values ​​to the condition.

SELECT… WHERE [NOT ] BETWEEN <f 1> AND <f 2>

For example, when obtaining the data whose field COL is 1~10, it can be written as WHERE COL BETWEEN 1 AND 10.

  1. string comparison

Use the LIKE statement when comparing strings. To obtain data starting with ABC, you can add the following conditions.

COL2='ABCDEFGHIGJ".

SELECT~ WHERE COL2 LIKE ‘ABC%’.

To obtain a 4-digit long string starting with ABC, for example, the symbol '_' can be used when comparing only one bit in ABCD, ABCE, AFCF, ABCG and other data.

WHERE COL2 LIKE 'ABC_ ’

  1. LIST VALUE

The IN statement can be used to obtain data that meets various conditions. For example, the condition for reading people living in 'Beijing' and 'Shanghai' may be "WHERE address IN('Beijing', 'Shanghai'")".

SELECT…WHERE[NOT] IN(<f 1>, …,) …

  1. SELECTION TABLE

Use the IN statement to query the data stored in the Selection Table and Range variables. Selection Table, Range variables are similar to internal tables, which can store multiple pieces of data.

SELECT… WHERE[NOT ] IN …

  1. dynamic condition

The WHERE condition of the SELECT statement can be written dynamically. The itab in the following statement can be defined as an internal table with a maximum size of 72 bits.

SELECT… WHERE () …

Refer to [Example 8] and [Example 9] to learn the program of dynamically giving query conditions.

*[例8]
REPORT z0_08.
DATA gs _where TYPE c LENGTH 72.DATA gv_carrname TYPE scarr-carrname.
DATA gv_carrid TYPE scarr-carrid VALUE'AC".
CONCATENATE 'CARRID=''' gv_carrid'''' INTO gs_where.
SELECT SINGLE carrname
INTO gv_carrname
FROM scarr
WHERE (gs_where).
WRITE / gv carrname.

[Result 8]
Air Canada
[Example 3-8] is to read the SELECT statement whose field value CARRID is equal to AC in the database table SCARR, where the WHERE condition is given dynamically. When more than two query conditions need to be given, the query conditions should be added to the inner table for use, as shown in [Example 3-9].
[Example 9]

*[例9]
REPORT z03_09.
DATA gs _whereTYPE c LENGTH 72.
DATA gt_where LIKE TABLE OF gs _where.DATA gv_carrname TYPE scarr-carrname.
DATA gv_carrid1 TYPE scarr-carrid VALUE'AC'.
DATA gv_carrid2TYPE scarr-carrid VALUE'AF".
CONCATENATE 'CARRID=''' gv_carrid1'''' INTO gs_where.
APPEND gs _where TO gt_where.
gs _where = 'OR'.
APPEND gs _where TO gt_where.
CONCATENATE 'CARRID =''' gv_carrid2'''' INTO gs_where.
APPEND gs _where TO gt_where.
SELECT carrname
INTO gv_carrname FROM scarr
WHERE (gt_where).
WRITE / gv_ carrname.ENDSELECT.

[Result 9]
Air Canada
Air France

  1. FOR ALL ENTRIES statement

SELECT…FOR ALL ENTRIES IN WHERE

FOR ALL ENTRYStatements function similarly to nested SELECT statements or Subqueries.
When using FOR ALL ENTRYa statement, the condition used in the WHERE statement must be a field that exists in itab.
Notice

  • The fields of itab must be of the same type as the table fields of the comparison object.
    - You cannot use comparison statements like LIKE, BETWEEN, IN, etc.
  • Duplicate data is automatically removed in itab (Unique Key is the benchmark). - If itab is empty, all data will be obtained.
  • When there is a lot of data in itab, the number of LOOP cycles will increase, so the selection speed will be reduced.

For example, itabif there are 3 pieces of data, it will be executed 3 times “SELECT ~ ENDSELECT”. [Example 10] is the program that inquires about all the data in
the database table storing the flight timetable and then queries relevant data from the date-based flight operation information database table with a statement.spfliFOR ALL ENTRIES

*[例10]
REPORT z03_10.
DATA gt_spfli TYPE TABLE OF spfli.
DATA gt_sflight TYPE TABLE OF sflight.DATA gs_sflight TYPE sflight.
SELECT * FROM spfli
INTO TABLE gt_spfli.
SELECT * FROM sflight INTO TABLE gt_sflight
FOR ALL ENTRIES IN gt_spfli
WHERE carrid = gt_spfli-carrid
AND connid = gt_spfli-connid.
LOOP AT gt_sflight INTO gs _sflight.
wWRITE: / gs _sflight-carrid, gs_sflight-connid.
ENDLOOP.

2.5 GROUPING statement

Before using Aggregatefunctions, you need to use GROUP BYstatements to group when selecting data. GROUP BYThe statement is to display the value in a row when the same value exists in a particular field of the table.

SELECT…
GROUP BY …

GROUP BYThe fields used after the statement must be queried in the SELECT statement. Fields and functions can be used in the statement
. Please refer to [Table 5] for functions. Statements can also be specified dynamically .SELECT
Aggregate
table 5
GROUP BY

GROUP BY(itab)…

Let's practice to obtain the average reservation occupancy rate of each flight ID separately. [Example 11]

REPORT z0_11.
DATA:gv_carrid TYPE sflight-carrid,
gv_connid TYPE sflight-connid,
gv_paymentsum TYPE i.
SELECT carrid connid AVG( paymentsum ) INTO (gv_carrid,gv_connid,gv_paymentsum)
FROM sflight 
GROUP BY carrid connid.
WRITE: / gv_carrid, gv_connid, gv_paymentsum.
ENDSELECT.

[Result 3-11]
AA 0017 136,905
AA 0064 90,139
AZ 0555 33,741
AZ 0788 320,638
When OPEN SQLusing SUMthe function in NTO CORRESPONDING FIELDS OFTABLEthe statement, the expected result cannot be obtained.
At this time, use the AS statement to give the aggregated field an alias, and the specific usage method is shown in the following code.

SELECT CARRID
SUM( PRICE ) AS PRICEFROM SFLIGHT
INTO CORRESPONDING FIELDS OF TABLE GT_GLT WHERE CARRID = ‘AA’.

2.6 GROUPINGConditional statements——HAVING

HAVINGIt is GROUP BYa conditional statement used when querying data by statement grouping. Similar to the WHERE conditional statement, its conditions can be defined dynamically.

SELECT-…
GROUP BY<f 2>HAVING .

The implementation method for obtaining the data whose average occupancy rate is greater than 100,000 in [Example 11] is as follows.

SELECT carrid connid AVG( paymentsum )
INTO (gv_carrid, gv_connid,gv_paymentsum) FROM sflight 
GROUP BY carrid connid 
HAVING AVG( paymentsum ) > 100000.

2.7 SORT statement

When using ORDER BYa statement when querying data, the query results will ORDER BYbe sorted according to the specified field. If you do not use ORDER BY, the sorting results will be displayed arbitrarily.
ORDER BY PRIMARY KEY
– Sort according to the KEY value of the table. -Only applies to SELECT* statements.
- Cannot be used in JOIN statements and views.

SELECT *
ORDER BY PRIMARY KEY.

All fields can be used in ORDER BY. With ASCENDING, DESCENDING statement can specify the sorting type, such as ascending, descending.

SELECT…ORDER BY[ASCENDING|DESCENDING]<2>IASCENDING|DESCENDINGl …

It is also possible to define the ORDER BY statement dynamically. The internal table type used should be char and the length cannot exceed 72 bits.

SELECT …ORDER BY (itab)

Use [Example 12] to practice making a program that sorts in ascending order based on reserved seats.
[Example 12]

*[例12]
REPORT Z03_12.
DATA:gv_carrid
TYPE sflight-carrid,
gv_connid
TYPE sflight-connid,
gY_paymentsum TYPE i.
SELECT carrid connid AVG( paymentsum ) as paymentsum
INTO (gv_carrid, gv_connid,gv_paymentsum)
FROM sflight
GROUP BY carrid connid
ORDER BY paymentsum.
WRITE:/ gv_carrid, gv_connid,gv_paymentsum.
ENDSELECT.

[Result 12]
Az 0555 33,741
LH 2407 38,371
LH 2402 79,572
DL1699 80,025
Because the functions such as etc. ORDER BYcannot be used in the statement , the AS statement must be used as an alias when querying data .AVG(paymentsum)Aggregate“paymentsum”

2.8 Subqueries

Subqueries are used when SELECTnesting statements within statements SELECT.
1. Scalar Subquery
Use subquery to WHEREadd special conditions to the statement. SubqueryOnly one field can be specified in the SELECTstatement.
Definition of Scalar Subquery
Scalar Subquery refers to the SELECT statement nested in the SELECT statement. It returns a field value (or function execution result value)
in a column of values , so the execution result is similar to the JOIN statement. Understanding of Scalar subqueryAggregate

  1. Scalar subquery can only return one field value.
  2. Scalar subqueries are executed in nested loops.
  3. The number of executions of Scalar subquery is the number of rows.
  4. Using this statement can greatly improve efficiency when querying repeated numbers and master data tables. Next, learn how to use Scalar Subquery through [Example 3-13].
*「例13]
REPORT z03_13.
DATA:gv_carridTYPE sflight-carrid,
gv_connidTYPE sflight-connid,
gV_pay mentsun TYPE sflight-paymentsum.
SELECT SINGLE carrid connid paymentsumINTO(gv_carrid , gv_connid, gv_paymentsum)FROM sflight AS a
WHERE carrid IN ( SELECT carrid
FROM spfli
WHEREcarid = a-carridAND connid= a-connid )AND a-carrid = 'AA'.
WRITE: gv_carrid, gv_connid, gv paymentsum.

2.Non-scalar Subquery
returns TRUE when the data queried by Subquery exists, and returns FALSE when it does not exist.
Use the EXISTS statement to realize, please refer to [Example 3-14] for the specific method.
[Example 14]

*[例14]
REPORT Z03_14.
DATA:gv_carrid TYPE sflight-carrid,
gv_connid TYPE sflight-connid,
gv_paymentsum TYPE sflight-paymentsum.
SELECT SINGLE carrid connid paymentsumINTO (gv_carrid , gv_connid,gv_paymentsum)
FROM sflight AS a
WHERE EXISTS ( SELECT*FROM spfli
wWHERE carrid = a-carridAND connid= a-connid ,AND a-carrid = 'AA'.
WRITE:gv_carrid,gv_connid,gv_paymentsum.

Guess you like

Origin blog.csdn.net/agelee/article/details/132690797