

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# 지원되는 SQL 및 PPL 명령
<a name="direct-query-supported-commands"></a>

OpenSearch SQL 및 OpenSearch 파이프라인 처리 언어(PPL)는 OpenSearch, CloudWatch Logs Insights 및 Security Lake에서 데이터를 쿼리, 분석 및 처리하기 위한 언어입니다. OpenSearch Discover에서 OpenSearch SQL 및 OpenSearch PPL을 사용하여 CloudWatch Logs, Amazon S3 또는 Security Lake 내에서 데이터를 쿼리할 수 있습니다. 또한 CloudWatch Logs Insights는 CloudWatch Logs 분석을 위해 특별히 구축된 쿼리 언어인 Logs Insights QL 외에, OpenSearch PPL 및 OpenSearch SQL 쿼리 언어까지 모두 지원합니다.
+ **OpenSearch SQL**: OpenSearch SQL은 관계형 데이터베이스 작업에 사용되는 익숙한 옵션을 제공합니다. OpenSearch SQL은 SQL 기능의 하위 집합을 제공하므로 임시 쿼리 및 데이터 분석 작업을 수행하는 데 적합합니다. OpenSearch SQL을 사용하면 SELECT, FROM, WHERE, GROUP BY, HAVING 등의 명령과 SQL에서 지원되는 기타 다양한 SQL 명령 및 함수를 사용할 수 있습니다. 테이블(또는 로그 그룹) 간에 JOIN을 실행하고, 하위 쿼리를 사용하여 테이블(또는 로그 그룹) 간에 데이터를 상호 연관시키고, 풍부한 JSON, 수학, 문자열, 조건부 및 기타 SQL 함수 세트를 사용하여 로그 및 보안 데이터에 대한 강력한 분석을 수행할 수 있습니다.
+ **OpenSearch 파이프 처리 언어(PPL):** OpenSearch PPL을 사용하면 파이프 조합 명령으로 데이터를 검색, 쿼리 및 분석할 수 있으므로 복잡한 쿼리를 더 쉽게 이해하고 구성할 수 있습니다. 구문은 Unix 파이프를 기반으로 하며 데이터를 변환하고 처리하기 위한 명령 체인을 활성화합니다. PPL을 사용하면 데이터를 필터링하고 집계할 수 있으며, JOIN, 하위 쿼리, LookUP 및 풍부한 수학, 문자열, 날짜, 조건부 및 기타 함수 집합과 같은 명령을 분석에 사용할 수 있습니다.

OpenSearch PPL 및 OpenSearch SQL 쿼리 언어의 명령은 대부분 CloudWatch Logs 및 OpenSearch에서 공통적이지만, 이들 각 서비스에서 지원되는 명령 및 함수 집합에는 몇 가지 차이점이 있습니다. 자세한 내용은 다음 페이지의 표를 참조하세요.

****
+ [지원되는 OpenSearch SQL 명령 및 함수](supported-directquery-sql.md)
  + [OpenSearch SQL을 사용하는 CloudWatch Logs Insights 사용자를 위한 추가 정보](supported-directquery-sql.md#supported-sql-for-multi-log-queries)
  + [일반 SQL 제한 사항](supported-directquery-sql.md#general-sql-restrictions)
+ [지원되는 PPL 명령](supported-ppl.md)
  + [OpenSearch PPL을 사용하는 CloudWatch Logs Insights 사용자를 위한 추가 정보](supported-ppl.md#supported-ppl-for-cloudwatch-users)

# 지원되는 OpenSearch SQL 명령 및 함수
<a name="supported-directquery-sql"></a>

다음 참조 표에는 Amazon S3, Security Lake 또는 CloudWatch Logs의 데이터 쿼리용으로 OpenSearch Discover에서 지원되는 SQL 명령과 CloudWatch Logs Insights에서 지원되는 SQL 명령이 나와 있습니다. CloudWatch Logs Insights에서 지원되는 SQL 구문과 CloudWatch Logs 쿼리용으로 OpenSearch Discover에서 지원되는 SQL 구문은 동일하며, 다음 표에 CloudWatch Logs로 표시됩니다.

**참고**  
OpenSearch는 OpenSearch에서 수집되어 인덱스에 저장된 데이터를 쿼리하기 위한 SQL 지원 기능도 제공합니다. 이 SQL 언어는 직접 쿼리에 사용되는 SQL과 다르며 [인덱스에서는 OpenSearch SQL](https://opensearch.org/docs/latest/search-plugins/sql/sql/index/)이라고 합니다.

**Topics**
+ [

## 명령
](#supported-sql-data-retrieval)
+ [

## 함수
](#supported-sql-functions)
+ [

## 일반 SQL 제한 사항
](#general-sql-restrictions)
+ [

## OpenSearch SQL을 사용하는 CloudWatch Logs Insights 사용자를 위한 추가 정보
](#supported-sql-for-multi-log-queries)

## 명령
<a name="supported-sql-data-retrieval"></a>

**참고**  
필요에 따라, 예의 명령 열에서 쿼리하려는 데이터 소스에 따라 `<tableName/logGroup>`을 바꿉니다.  
명령 예: `SELECT Body , Operation FROM <tableName/logGroup>` 
Amazon S3 또는 Security Lake를 쿼리하는 경우 `SELECT Body , Operation FROM table_name`을 사용합니다.
CloudWatch Logs를 쿼리하는 경우 `SELECT Body , Operation FROM `LogGroupA``를 사용합니다.


| 명령 | 설명 | CloudWatch Logs | Amazon S3 | Security Lake |  명령 예제 | 
| --- | --- | --- | --- | --- | --- | 
|  [SELECT 절](#supported-sql-select)  |  예상 값을 표시합니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    method,<br />    status <br />FROM <br />    <tableName/logGroup></pre>  | 
| [WHERE 절](#supported-sql-where) |  제공된 필드 기준에 따라 로그 이벤트를 필터링합니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    * <br />FROM <br />    <tableName/logGroup><br />WHERE <br />    status = 100</pre>  | 
| [GROUP BY 절](#supported-sql-group-by) |  범주를 기반으로 로그 이벤트를 그룹화하고 통계를 기반으로 평균을 찾습니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    method,<br />    status,<br />    COUNT(*) AS request_count,<br />    SUM(bytes) AS total_bytes <br />FROM <br />    <tableName/logGroup> <br />GROUP BY <br />    method, <br />    status</pre>  | 
| [HAVING 절](#supported-sql-having) |  그룹화 조건을 기준으로 결과를 필터링합니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    method,<br />    status,<br />    COUNT(*) AS request_count,<br />    SUM(bytes) AS total_bytes <br />FROM <br />    <tableName/logGroup> <br />GROUP BY <br />    method,<br />    status<br />HAVING <br />    COUNT(*) > 5</pre>  | 
| [ORDER BY 절](#supported-sql-order-by) |  order 절의 필드에 따라 결과를 정렬합니다. 오름차순 또는 내림차순으로 정렬할 수 있습니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    * <br />FROM <br />    <tableName/logGroup> <br />ORDER BY <br />    status DESC</pre>  | 
|  [JOIN 절](#supported-sql-join)  ( `INNER` \$1 `CROSS` \$1 `LEFT` `OUTER` )  |  공통 필드를 기반으로 두 테이블의 결과를 조인합니다.  |  ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨(조인에 `Inner` 및 `Left Outer` 키워드를 사용해야 함, SELECT 문에서는 하나의 JOIN 작업만 지원됨)  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨(조인에 내부, 왼쪽 외부 및 교차 키워드를 사용해야 함) | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨(조인에 내부, 왼쪽 외부 및 교차 키워드를 사용해야 함) |  <pre>SELECT <br />    A.Body,<br />    B.Timestamp<br />FROM <br />    <tableNameA/logGroupA> AS A <br />INNER JOIN <br />    <tableNameB/logGroupB> AS B <br />    ON A.`requestId` = B.`requestId`</pre>  | 
| [LIMIT 절](#supported-sql-limit) |  결과를 첫 번째 N개 행으로 제한합니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    * <br />FROM <br />    <tableName/logGroup> <br />LIMIT <br />    10</pre>  | 
| [CASE 절](#supported-sql-case) | 조건을 평가하고 첫 번째 조건이 충족되면 값을 반환합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT<br />    method,<br />    status,<br />    CASE<br />        WHEN status BETWEEN 100 AND 199 THEN 'Informational'<br />        WHEN status BETWEEN 200 AND 299 THEN 'Success'<br />        WHEN status BETWEEN 300 AND 399 THEN 'Redirection'<br />        WHEN status BETWEEN 400 AND 499 THEN 'Client Error'<br />        WHEN status BETWEEN 500 AND 599 THEN 'Server Error'<br />        ELSE 'Unknown Status'<br />    END AS status_category,<br />    CASE method<br />        WHEN 'GET' THEN 'Read Operation'<br />        WHEN 'POST' THEN 'Create Operation'<br />        WHEN 'PUT' THEN 'Update Operation'<br />        WHEN 'PATCH' THEN 'Partial Update Operation'<br />        WHEN 'DELETE' THEN 'Delete Operation'<br />        ELSE 'Other Operation'<br />    END AS operation_type,<br />    bytes,<br />    datetime<br />FROM <tableName/logGroup>                         </pre>  | 
| [공통 테이블 표현식](#supported-sql-cte) | SELECT, INSERT, UPDATE, DELETE 또는 MERGE 문 내에 명명된 임시 결과 세트를 생성합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.svg) 지원되지 않음 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>WITH RequestStats AS (<br />    SELECT <br />        method,<br />        status,<br />        bytes,<br />        COUNT(*) AS request_count<br />    FROM <br />        tableName<br />    GROUP BY <br />        method,<br />        status,<br />        bytes<br />)<br />SELECT <br />    method,<br />    status,<br />    bytes,<br />    request_count <br />FROM <br />    RequestStats <br />WHERE <br />    bytes > 1000</pre>  | 
| [EXPLAIN](#supported-sql-explain) | 실제로 실행하지 않고 SQL 문의 실행 계획을 표시합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.svg) 지원되지 않음 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>EXPLAIN<br />SELECT <br />    k,<br />    SUM(v)<br />FROM <br />    VALUES <br />        (1, 2),<br />        (1, 3) AS t(k, v)<br />GROUP BY <br />    k</pre>  | 
| [LATERAL SUBQUERY 절](#supported-sql-lateral-subquery) | FROM 절의 하위 쿼리가 동일한 FROM 절의 이전 항목에서 열을 참조하도록 허용합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.svg) 지원되지 않음 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre> SELECT <br />    * <br />FROM <br />    tableName<br />LATERAL (<br />    SELECT <br />        * <br />    FROM <br />        t2 <br />    WHERE <br />        t1.c1 = t2.c1<br />)</pre>  | 
| [LATERAL VIEW 절](#supported-sql-lateral-view) | 기본 테이블의 각 행에 테이블 생성 함수를 적용하여 가상 테이블을 생성합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.svg) 지원되지 않음 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    * <br />FROM <br />    tableName<br />LATERAL VIEW <br />    EXPLODE(ARRAY(30, 60)) tableName AS c_age<br />LATERAL VIEW <br />    EXPLODE(ARRAY(40, 80)) AS d_age</pre>  | 
| [LIKE 조건자](#supported-sql-like-predicate) | 와일드카드 문자를 사용하여 문자열을 패턴과 매칭합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre> SELECT <br />    method,<br />    status,<br />    request,<br />    host <br />FROM <br />    <tableName/logGroup> <br />WHERE <br />    method LIKE 'D%'</pre>  | 
| [OFFSET](#supported-sql-offset) | 쿼리에서 행을 반환하기 전에 건너뛸 행 수를 지정합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 쿼리에서 LIMIT 절과 함께 사용할 때 지원됨 예제:[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/supported-directquery-sql.html) | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre> SELECT <br />    method,<br />    status,<br />    bytes,<br />    datetime <br />FROM <br />    <tableName/logGroup> <br />ORDER BY <br />    datetime<br />OFFSET <br />    10 </pre>  | 
| [PIVOT 절](#supported-sql-pivot) | 행을 열로 변환하여 데이터를 행 기반 형식에서 열 기반 형식으로 바꿉니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.svg) 지원되지 않음 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    * <br />FROM <br />    (<br />        SELECT <br />            method,<br />            status,<br />            bytes<br />        FROM <br />            <tableName/logGroup><br />    ) AS SourceTable <br />PIVOT <br />(<br />    SUM(bytes) <br />    FOR method IN ('GET', 'POST', 'PATCH', 'PUT', 'DELETE')<br />) AS PivotTable</pre>  | 
| [집합 연산자](#supported-sql-set) | 2개 이상의 SELECT 문(예: UNION, INTERSECT, EXCEPT)의 결과를 결합합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    method,<br />    status,<br />    bytes<br />FROM <br />    <tableName/logGroup><br />WHERE <br />    status = '416'<br /><br />UNION<br /><br />SELECT <br />    method,<br />    status,<br />    bytes<br />FROM <br />    <tableName/logGroup><br />WHERE <br />    bytes > 20000</pre>  | 
| [SORT BY 절](#supported-sql-sort-by) | 쿼리 결과를 반환할 순서를 지정합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    method,<br />    status,<br />    bytes<br />FROM <br />    <tableName/logGroup><br />SORT BY <br />    bytes DESC</pre>  | 
| [UNPIVOT](#supported-sql-unpivot) | 열을 행으로 변환하여 데이터를 열 기반 형식에서 행 기반 형식으로 바꿉니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.svg) 지원되지 않음 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre> SELECT <br />    status,<br />    REPLACE(method, '_bytes', '') AS request_method,<br />    bytes,<br />    datetime <br />FROM <br />    PivotedData <br />UNPIVOT <br />(<br />    bytes <br />    FOR method IN <br />    (<br />        GET_bytes,<br />        POST_bytes,<br />        PATCH_bytes,<br />        PUT_bytes,<br />        DELETE_bytes<br />    )<br />) AS UnpivotedData</pre>  | 

## 함수
<a name="supported-sql-functions"></a>

**참고**  
필요에 따라, 예의 명령 열에서 쿼리하려는 데이터 소스에 따라 `<tableName/logGroup>`을 바꿉니다.  
명령 예: `SELECT Body , Operation FROM <tableName/logGroup>` 
Amazon S3 또는 Security Lake를 쿼리하는 경우 `SELECT Body , Operation FROM table_name`을 사용합니다.
CloudWatch Logs를 쿼리하는 경우 `SELECT Body , Operation FROM `LogGroupA``를 사용합니다.


| 사용 가능한 SQL 문법 | 설명 | CloudWatch Logs | Amazon S3 | Security Lake |  명령 예제 | 
| --- | --- | --- | --- | --- | --- | 
| [문자열 함수](#supported-sql-string) |  SQL 쿼리 내에서 문자열 및 텍스트 데이터를 조작하고 변환할 수 있는 내장 함수입니다. 변환 사례, 문자열 결합, 부분 추출, 텍스트 정리 등을 예로 들 수 있습니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    UPPER(method) AS upper_method,<br />    LOWER(host) AS lower_host <br />FROM <br />    <tableName/logGroup></pre>  | 
| [날짜 및 시간 함수](#supported-sql-date-time) |  쿼리에서 날짜 및 타임스탬프 데이터를 처리하고 변환하는 내장 함수입니다. 예: **date\$1add**, **date\$1format**, **datediff**, **current\$1date**.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    TO_TIMESTAMP(datetime) AS timestamp,<br />    TIMESTAMP_SECONDS(UNIX_TIMESTAMP(datetime)) AS from_seconds,<br />    UNIX_TIMESTAMP(datetime) AS to_unix,<br />    FROM_UTC_TIMESTAMP(datetime, 'PST') AS to_pst,<br />    TO_UTC_TIMESTAMP(datetime, 'EST') AS from_est <br />FROM <br />    <tableName/logGroup></pre>  | 
| [집계 함수](#supported-sql-aggregate) |  여러 행에서 계산을 수행하여 단일 요약 값을 생성하는 내장 함수입니다. 예: **sum**, **count**, **avg**, **max**, **min**.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg)지원됨 |  ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    COUNT(*) AS total_records,<br />    COUNT(DISTINCT method) AS unique_methods,<br />    SUM(bytes) AS total_bytes,<br />    AVG(bytes) AS avg_bytes,<br />    MIN(bytes) AS min_bytes,<br />    MAX(bytes) AS max_bytes <br />FROM <br />    <tableName/logGroup></pre>  | 
| [조건 함수](#supported-sql-conditional) |  지정된 조건을 기반으로 작업을 수행하거나 조건부로 표현식을 평가하는 내장 함수입니다. 예: **CASE**, **IF**.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    CASE <br />        WHEN method = 'GET' AND bytes < 1000 THEN 'Small Read'<br />        WHEN method = 'POST' AND bytes > 10000 THEN 'Large Write'<br />        WHEN status >= 400 OR bytes = 0 THEN 'Problem'<br />        ELSE 'Normal'<br />    END AS request_type <br />FROM <br />    <tableName/logGroup></pre>  | 
| [JSON 함수](#supported-sql-json) |  데이터 세트에서 JSON 구조를 조작할 수 있도록 SQL 쿼리(예: from\$1json, to\$1json, get\$1json\$1object, json\$1tuple) 내에서 JSON 형식 데이터를 구문 분석, 추출, 수정 및 쿼리하는 기본 제공 함수입니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    FROM_JSON(<br />        @message, <br />        'STRUCT<<br />            host: STRING,<br />            user-identifier: STRING,<br />            datetime: STRING,<br />            method: STRING,<br />            status: INT,<br />            bytes: INT<br />        >'<br />    ) AS parsed_json <br />FROM <br />    <tableName/logGroup> </pre>  | 
| [배열 함수](#supported-sql-array) |  SQL 쿼리에서 배열 유형 열 작업에 내장 함수를 사용하면 배열 데이터 액세스, 수정 및 분석과 같은 작업(예: 크기, 폭발, array\$1contains)을 수행할 수 있습니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    scores,<br />    size(scores) AS length,<br />    array_contains(scores, 90) AS has_90 <br />FROM <br />    <tableName/logGroup></pre>  | 
| [윈도우 함수](#supported-sql-window) | 현재 행(윈도우)과 관련된 지정된 행 세트에서 계산을 수행하여 순위, 합계 실행 및 이동 평균(예: ROW\$1NUMBER, RANK, LAG, LEAD)과 같은 작업을 활성화하는 내장 함수입니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre> SELECT <br />    field1,<br />    field2,<br />    RANK() OVER (ORDER BY field2 DESC) AS field2Rank <br />FROM <br />    <tableName/logGroup></pre>  | 
| [변환 함수](#supported-sql-conversion) |  SQL 쿼리 내에서 한 유형에서 다른 유형으로 데이터를 변환하여 데이터 유형 변환 및 형식 변환을 지원하는 내장 함수(예: CAST, TO\$1DATE, TO\$1TIMESTAMP, BINARY)입니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    CAST('123' AS INT) AS converted_number,<br />    CAST(123 AS STRING) AS converted_string <br />FROM <br />    <tableName/logGroup></pre>  | 
| [조건자 함수](#supported-sql-predicate) |  조건을 평가하고 지정된 기준 또는 패턴(예: IN, LIKE, BETWEEN, IS NULL, EXISTS)에 따라 부울 값(true/false)을 반환하는 내장 함수입니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    * <br />FROM <br />    <tableName/logGroup> <br />WHERE <br />    id BETWEEN 50000 AND 75000</pre>  | 
| [맵 함수](#supported-sql-map) | 컬렉션의 각 요소에 지정된 함수를 적용하여 데이터를 새 값 세트로 변환합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.svg) 지원되지 않음 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    MAP_FILTER(<br />        MAP(<br />            'method', method,<br />            'status', CAST(status AS STRING),<br />            'bytes', CAST(bytes AS STRING)<br />        ),<br />        (k, v) -> k IN ('method', 'status') AND v != 'null'<br />    ) AS filtered_map <br />FROM <br />    <tableName/logGroup> <br />WHERE <br />    status = 100</pre>  | 
| [수학 함수](#supported-sql-math) | 평균, 합계, 삼각함수 값 계산 등, 숫자 데이터에 대한 수학 연산을 수행합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    bytes,<br />    bytes + 1000 AS added,<br />    bytes - 1000 AS subtracted,<br />    bytes * 2 AS doubled,<br />    bytes / 1024 AS kilobytes,<br />    bytes % 1000 AS remainder <br />FROM <br />    <tableName/logGroup></pre>  | 
| [다중 로그 그룹 함수](#multi-log-queries) |  사용자가 SQL SELECT 문에서 여러 로그 그룹을 지정할 수 있도록 합니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | 해당 사항 없음 | 해당 사항 없음 |  <pre>SELECT <br />    lg1.Column1,<br />    lg1.Column2 <br />FROM <br />    `logGroups(logGroupIdentifier: ['LogGroup1', 'LogGroup2'])` AS lg1 <br />WHERE <br />    lg1.Column3 = "Success"<br /></pre>  | 
| [생성 함수](#supported-sql-generator) | 값 시퀀스를 생성하는 반복자 객체를 생성하여 대규모 데이터 세트에서 메모리를 효율적으로 사용할 수 있게 합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.svg) 지원되지 않음 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>SELECT <br />    explode(array(10, 20)) </pre>  | 

## 일반 SQL 제한 사항
<a name="general-sql-restrictions"></a>

CloudWatch Logs, Amazon S3 및 Security Lake와 함께 OpenSearch SQL을 사용할 경우 다음 제한이 적용됩니다.

1. SELECT 문에는 하나의 JOIN 작업만 사용할 수 있습니다.

1. 중첩 하위 쿼리는 한 수준만 지원됩니다.

1. 세미콜론으로 구분된 여러 문 쿼리는 지원되지 않습니다.

1. 동일하지만 대/소문자만 다른 필드 이름을 포함하는 쿼리(예: field1과 FIELD1)는 지원되지 않습니다.

   예를 들어 다음 쿼리는 지원되지 않습니다.

   ```
   Select AWSAccountId, awsaccountid from LogGroup
   ```

   단, 다음 쿼리는 필드 이름(@logStream)이 두 로그 그룹에서 동일하기 때문에 지원됩니다.

   ```
   Select a.`@logStream`, b.`@logStream` from Table A INNER Join Table B on a.id = b.id 
   ```

1. 함수와 표현식은 필드 이름에 대해 작동해야 하며 FROM 절에 지정된 로그 그룹이 있는 SELECT 문의 일부여야 합니다.

   예를 들어 다음 쿼리는 지원되지 않습니다.

   ```
   SELECT cos(10) FROM LogGroup
   ```

   다음 쿼리는 지원됩니다.

   ```
   SELECT cos(field1) FROM LogGroup
   ```

## OpenSearch SQL을 사용하는 CloudWatch Logs Insights 사용자를 위한 추가 정보
<a name="supported-sql-for-multi-log-queries"></a>

 CloudWatch Logs는 Logs Insights 콘솔, API 및 CLI에서 OpenSearch SQL 쿼리를 지원합니다. SELECT, FROM, WHERE, GROUP BY, HAVING, JOINS 및 중첩 쿼리를 비롯한 대부분의 명령과 JSON, 수학, 문자열 및 조건 함수를 지원합니다. 단, CloudWatch Logs는 읽기 작업만 지원하므로 DDL 또는 DML 문은 허용되지 않습니다. 지원되는 명령 및 함수의 전체 목록은 이전 섹션의 표를 참조하세요.

### 다중 로그 그룹 함수
<a name="multi-log-queries"></a>

CloudWatch Logs Insights는 여러 로그 그룹을 쿼리하는 기능을 지원합니다. SQL에서는 `logGroups` 명령을 사용하여 이 사용 사례를 해결할 수 있습니다. 이 명령은 하나 이상의 로그 그룹과 관련한 CloudWatch Logs Insights의 데이터 쿼리에만 해당됩니다. 이 구문을 사용하면 각 로그 그룹에 대한 쿼리를 작성하고 `UNION` 명령과 결합하는 대신 명령에 지정하여 여러 로그 그룹을 쿼리할 수 있습니다.

구문:

```
`logGroups(
    logGroupIdentifier: ['LogGroup1','LogGroup2', ...'LogGroupn']
)
```

이 구문에서는 `logGroupIndentifier` 파라미터에 최대 50개의 로그 그룹을 지정할 수 있습니다. 모니터링 계정의 로그 그룹을 참조하려면 `LogGroup` 이름 대신 ARN을 사용합니다.

예제 쿼리:

```
SELECT LG1.Column1, LG1.Column2 from `logGroups(
    logGroupIdentifier: ['LogGroup1', 'LogGroup2']
)` as LG1 
WHERE LG1.Column1 = 'ABC'
```

CloudWatch Logs를 쿼리할 때 `FROM` 문 뒤에 여러 로그 그룹이 포함된 다음 구문은 지원되지 않습니다.

```
SELECT Column1, Column2 FROM 'LogGroup1', 'LogGroup2', ...'LogGroupn' 
WHERE Column1 = 'ABC'
```

### 제한 사항
<a name="restrictions"></a>

SQL 또는 PPL 명령을 사용하는 경우 특정 필드를 백틱으로 묶어 쿼리합니다. 백틱은 특수 문자(비영숫자 및 비숫자)가 있는 필드에 필요합니다. 예를 들어 `@message`, `Operation.Export,` 및 `Test::Field`는 백틱으로 묶습니다. 알파벳으로만 된 이름의 열을 백틱으로 묶을 필요는 없습니다.

단순 필드가 있는 쿼리 예:

```
SELECT SessionToken, Operation, StartTime  FROM `LogGroup-A`
LIMIT 1000;
```

백틱이 추가된 동일한 쿼리:

```
SELECT `SessionToken`, `Operation`, `StartTime`  FROM `LogGroup-A`
LIMIT 1000;
```

CloudWatch Logs에만 국한되지 않는 추가적인 일반 제한 사항은 [일반 SQL 제한 사항](#general-sql-restrictions) 섹션을 참조하세요.

### 샘플 쿼리 및 할당량
<a name="samples"></a>

**참고**  
다음은 CloudWatch 데이터를 쿼리하는 CloudWatch Logs Insights 사용자와 OpenSearch 사용자 모두에게 적용됩니다.

CloudWatch Logs에서 사용할 수 있는 샘플 SQL 쿼리의 예는 Amazon CloudWatch Logs Insights 콘솔의 **저장된 쿼리 및 샘플 쿼리**를 참조하세요.

OpenSearch Service에서 CloudWatch Logs를 쿼리할 때 적용되는 제한에 대한 자세한 내용은 Amazon CloudWatch Logs 사용 설명서의 [CloudWatch Logs 할당량](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/cloudwatch_limits_cwl.html)을 참조하세요. 제한에는 쿼리할 수 있는 CloudWatch Log 그룹 수, 실행할 수 있는 최대 동시 쿼리 수, 최대 쿼리 실행 시간 및 결과에 반환된 최대 행 수가 포함됩니다. CloudWatch Logs를 쿼리하는 데 사용하는 언어(즉, OpenSearch PPL, SQL 및 Logs Insights)에 관계없이 제한은 동일합니다.

### SQL 명령
<a name="supported-sql-commands-details"></a>

**Topics**
+ [

#### 문자열 함수
](#supported-sql-string)
+ [

#### 날짜 및 시간 함수
](#supported-sql-date-time)
+ [

#### 집계 함수
](#supported-sql-aggregate)
+ [

#### 조건 함수
](#supported-sql-conditional)
+ [

#### JSON 함수
](#supported-sql-json)
+ [

#### 배열 함수
](#supported-sql-array)
+ [

#### 윈도우 함수
](#supported-sql-window)
+ [

#### 변환 함수
](#supported-sql-conversion)
+ [

#### 조건자 함수
](#supported-sql-predicate)
+ [

#### 맵 함수
](#supported-sql-map)
+ [

#### 수학 함수
](#supported-sql-math)
+ [

#### 생성 함수
](#supported-sql-generator)
+ [

#### SELECT 절
](#supported-sql-select)
+ [

#### WHERE 절
](#supported-sql-where)
+ [

#### GROUP BY 절
](#supported-sql-group-by)
+ [

#### HAVING 절
](#supported-sql-having)
+ [

#### ORDER BY 절
](#supported-sql-order-by)
+ [

#### JOIN 절
](#supported-sql-join)
+ [

#### LIMIT 절
](#supported-sql-limit)
+ [

#### CASE 절
](#supported-sql-case)
+ [

#### 공통 테이블 표현식
](#supported-sql-cte)
+ [

#### EXPLAIN
](#supported-sql-explain)
+ [

#### LATERAL SUBQUERY 절
](#supported-sql-lateral-subquery)
+ [

#### LATERAL VIEW 절
](#supported-sql-lateral-view)
+ [

#### LIKE 조건자
](#supported-sql-like-predicate)
+ [

#### OFFSET
](#supported-sql-offset)
+ [

#### PIVOT 절
](#supported-sql-pivot)
+ [

#### 집합 연산자
](#supported-sql-set)
+ [

#### SORT BY 절
](#supported-sql-sort-by)
+ [

#### UNPIVOT
](#supported-sql-unpivot)

#### 문자열 함수
<a name="supported-sql-string"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).


****  

| 함수 | 설명 | 
| --- | --- | 
| ascii(str) | str에서 첫 번째 문자의 숫자 값을 반환합니다. | 
| base64(bin) | 인수를 바이너리 bin에서 Base 64 문자열로 변환합니다. | 
| bit\$1length(expr) | 문자열 데이터의 비트 길이 또는 바이너리 데이터의 비트 수를 반환합니다. | 
| btrim(str) | str에서 선행 및 후행 공백 문자를 제거합니다. | 
| btrim(str, trimStr) | str에서 선행 및 후행 trimStr 문자를 제거합니다. | 
| char(expr) | expr과 동일한 바이너리를 가진 ASCII 문자를 반환합니다. n이 256보다 큰 경우 결과는 chr(n % 256)과 같습니다. | 
| char\$1length(expr) | 문자열 데이터의 문자 길이 또는 바이너리 데이터의 바이트 수를 반환합니다. 문자열 데이터의 길이는 후행 공백을 포함합니다. 바이너리 데이터의 길이는 바이너리 0을 포함합니다. | 
| character\$1length(expr) | 문자열 데이터의 문자 길이 또는 바이너리 데이터의 바이트 수를 반환합니다. 문자열 데이터의 길이는 후행 공백을 포함합니다. 바이너리 데이터의 길이는 바이너리 0을 포함합니다. | 
| chr(expr) | expr과 동일한 바이너리를 가진 ASCII 문자를 반환합니다. n이 256보다 큰 경우 결과는 chr(n % 256)과 같습니다. | 
| concat\$1ws(sep[, str \$1 array(str)]\$1) | null 값을 건너뛰고 sep로 구분된 문자열의 연결을 반환합니다. | 
| contains(left, right) | 부울을 반환합니다. right가 left 내에 있는 경우 값은 True입니다. 입력 표현식 중 하나가 NULL인 경우 NULL을 반환합니다. 그렇지 않을 경우 false를 반환합니다. left 또는 right 모두 STRING 또는 BINARY 유형이어야 합니다. | 
| decode(bin, charset) | 두 번째 인수 문자 집합을 사용하여 첫 번째 인수를 디코딩합니다. | 
| decode(expr, search, result [, search, result ] ... [, default]) | expr을 각 검색 값과 순서대로 비교합니다. expr이 검색 값과 같으면 디코딩에서 해당 결과를 반환합니다. 일치하는 항목이 없으면 기본값을 반환합니다. 기본값을 생략하면 null을 반환합니다. | 
| elt(n, input1, input2, ...) | n번째 입력을 반환합니다. 예를 들어 n이 2인 경우 input2를 반환합니다. | 
| encode(str, charset) | 두 번째 인수 문자 집합을 사용하여 첫 번째 인수를 인코딩합니다. | 
| endswith(left, right) | 부울을 반환합니다. left가 right로 끝나는 경우 값은 True입니다. 입력 표현식 중 하나가 NULL인 경우 NULL을 반환합니다. 그렇지 않을 경우 false를 반환합니다. left 또는 right 모두 STRING 또는 BINARY 유형이어야 합니다. | 
| find\$1in\$1set(str, str\$1array) | 쉼표로 구분된 목록(str\$1array)에서 지정된 문자열(str)의 인덱스(1 기반)를 반환합니다. 문자열을 찾을 수 없거나 지정된 문자열(str)에 쉼표가 포함된 경우 0을 반환합니다. | 
| format\$1number(expr1, expr2) | '\$1,\$1\$1\$1,\$1\$1\$1.\$1\$1'과 같은 숫자 expr1의 형식을 expr2 소수 자릿수로 반올림합니다. expr2가 0이면 결과에 소수점이나 소수 부분이 없는 것입니다. expr2에는 사용자 지정 형식도 허용됩니다. MySQL의 FORMAT처럼 작동합니다. | 
| format\$1string(strfmt, obj, ...) | printf 스타일 형식 문자열에서 형식이 지정된 문자열을 반환합니다. | 
| initcap(str) | 대문자로 된 각 단어의 첫 번째 문자와 함께 str을 반환합니다. 다른 모든 문자는 소문자입니다. 단어는 공백으로 구분됩니다. | 
| instr(str, substr) | str에서 substr의 첫 출현에 대해 (1 기반) 인덱스를 반환합니다. | 
| lcase(str) | 모든 문자가 소문자로 변경된 상태로 str을 반환합니다. | 
| left(str, len) | str 문자열에서 가장 왼쪽 len(len은 문자열 유형일 수 있음) 문자를 반환합니다. len이 0보다 작거나 같으면 빈 문자열이 결과로 반환됩니다. | 
| len(expr) | 문자열 데이터의 문자 길이 또는 바이너리 데이터의 바이트 수를 반환합니다. 문자열 데이터의 길이는 후행 공백을 포함합니다. 바이너리 데이터의 길이는 바이너리 0을 포함합니다. | 
| length(expr) | 문자열 데이터의 문자 길이 또는 바이너리 데이터의 바이트 수를 반환합니다. 문자열 데이터의 길이는 후행 공백을 포함합니다. 바이너리 데이터의 길이는 바이너리 0을 포함합니다. | 
| levenshtein(str1, str2[, threshold]) | 지정된 두 문자열 사이의 레벤슈타인 거리를 반환합니다. 임계값이 설정되어 있고 그보다 거리가 멀면 -1을 반환합니다. | 
| locate(substr, str[, pos]) | str의 위치 pos 뒤에서 substr의 첫 번째 출현 위치를 반환합니다. 지정된 pos 및 반환 값은 1 기반입니다. | 
| lower(str) | 모든 문자가 소문자로 변경된 상태로 str을 반환합니다. | 
| lpad(str, len[, pad]) | pad로 왼쪽 패딩된 str을 len 길이로 반환합니다. str이 len보다 길면 반환 값이 len 문자 또는 바이트로 단축됩니다. pad를 지정하지 않으면 str은 문자열인 경우 공백 문자로, 바이트 시퀀스인 경우 0으로 왼쪽에 패딩됩니다. | 
| ltrim(str) | str에서 선행 공백 문자를 제거합니다. | 
| luhn\$1check(str) | Luhn 알고리즘에 따라 숫자 문자열이 유효한지 확인합니다. 이 체크섬 함수는 신용카드 번호 및 정부 발행 신분증 번호에 광범위하게 적용되어 유효한 번호를 잘못 입력되거나 부정확한 번호와 구분합니다. | 
| mask(input[, upperChar, lowerChar, digitChar, otherChar]) | 지정된 문자열 값을 마스킹합니다. 이 함수는 문자를 'X' 또는 'x'로 바꾸고 숫자를 'n'으로 바꿉니다. 이 함수는 민감한 정보가 제거된 테이블의 복사본을 생성하는 데 유용할 수 있습니다. | 
| octet\$1length(expr) | 문자열 데이터의 바이트 길이 또는 바이너리 데이터의 바이트 수를 반환합니다. | 
| overlay(input, replace, pos[, len]) | input을 pos로 시작하고 길이가 len인 replace로 바꿉니다. | 
| position(substr, str[, pos]) | str의 위치 pos 뒤에서 substr의 첫 번째 출현 위치를 반환합니다. 지정된 pos 및 반환 값은 1 기반입니다. | 
| printf(strfmt, obj, ...) | printf 스타일 형식 문자열에서 형식이 지정된 문자열을 반환합니다. | 
| regexp\$1count(str, regexp) | 문자열 str에서 정규식 패턴 regexp가 일치하는 횟수를 반환합니다. | 
| regexp\$1extract(str, regexp[, idx]) | regexp 표현식과 일치하고 정규식 그룹 인덱스에 해당하는 str의 첫 번째 문자열을 추출합니다. | 
| regexp\$1extract\$1all(str, regexp[, idx]) | regexp 표현식과 일치하고 정규식 그룹 인덱스에 해당하는 str의 모든 문자열을 추출합니다. | 
| regexp\$1instr(str, regexp) | 문자열에서 정규식을 검색하여 일치하는 하위 문자열의 시작 위치를 나타내는 정수를 반환합니다. 위치는 0이 아닌 1 기반입니다. 일치하는 결과가 없는 경우 0을 반환합니다. | 
| regexp\$1replace(str, regexp, rep[, position]) | regexp와 일치하는 str의 모든 하위 문자열을 rep로 바꿉니다. | 
| regexp\$1substr(str, regexp) | 문자열 str 내의 정규식 regexp와 일치하는 하위 문자열을 반환합니다. 정규식을 찾을 수 없는 경우 결과는 null입니다. | 
| repeat(str, n) | 지정된 문자열 값을 n번 반복하는 문자열을 반환합니다. | 
| replace(str, search[, replace]) | 모든 search를 replace로 바꿉니다. | 
| right(str, len) | str 문자열에서 가장 오른쪽 len(len은 문자열 유형일 수 있음) 문자를 반환합니다. len이 0보다 작거나 같으면 빈 문자열이 결과로 반환됩니다. | 
| rpad(str, len[, pad]) | pad로 오른쪽 패딩된 str을 len 길이로 반환합니다. str이 len보다 길면 반환 값이 len 문자로 단축됩니다. pad를 지정하지 않으면 str은 문자열인 경우 공백 문자로, 바이너리 문자열인 경우 0으로 오른쪽에 패딩됩니다. | 
| rtrim(str) | str에서 후행 공백 문자를 제거합니다. | 
| sentences(str[, lang, country]) | str을 단어 배열로 분할합니다. | 
| soundex(str) | 문자열의 Soundex 코드를 반환합니다. | 
| space(n) | n개의 공백으로 구성된 문자열을 반환합니다. | 
| split(str, regex, limit) | regex와 일치하는 str을 분할하고 최대 limit 길이의 배열을 반환합니다. | 
| split\$1part(str, delimiter, partNum) | str을 구분 기호로 분할하고 분할의 요청된 부분(1 기반)을 반환합니다. 입력이 null이면 null을 반환합니다. partNum이 분할된 부분의 범위를 벗어나면 빈 문자열을 반환합니다. partNum이 0이면 오류가 발생합니다. partNum이 음수면 문자열 끝에서 역순으로 부분들이 계산됩니다. delimiter가 빈 문자열이면 str이 분할되지 않습니다. | 
| startswith(left, right) | 부울을 반환합니다. left가 right로 시작하는 경우 값은 True입니다. 입력 표현식 중 하나가 NULL인 경우 NULL을 반환합니다. 그렇지 않을 경우 false를 반환합니다. left 또는 right 모두 STRING 또는 BINARY 유형이어야 합니다. | 
| substr(str, pos[, len]) | pos에서 시작하고 길이가 len인의 하위 문자열 str 또는 pos에서 시작하고 길이가 len인 바이트 배열 조각을 반환합니다. | 
| substr(str FROM pos[ FOR len]]) | pos에서 시작하고 길이가 len인의 하위 문자열 str 또는 pos에서 시작하고 길이가 len인 바이트 배열 조각을 반환합니다. | 
| substring(str, pos[, len]) | pos에서 시작하고 길이가 len인의 하위 문자열 str 또는 pos에서 시작하고 길이가 len인 바이트 배열 조각을 반환합니다. | 
| substring(str FROM pos[ FOR len]]) | pos에서 시작하고 길이가 len인의 하위 문자열 str 또는 pos에서 시작하고 길이가 len인 바이트 배열 조각을 반환합니다. | 
| substring\$1index(str, delim, count) | 구분 기호 delim이 count회 나타나기 전에 str에서 하위 문자열을 반환합니다. count가 양수이면 최종 구분 기호 왼쪽에 있는 모든 항목(왼쪽부터 계산)이 반환됩니다. count가 음수이면 최종 구분 기호 오른쪽에 있는 모든 항목(오른쪽부터 계산)이 반환됩니다. 함수 substring\$1index는 delim을 검색할 때 대소문자를 구분하는 매칭을 수행합니다. | 
| to\$1binary(str[, fmt]) | 제공된 fmt에 따라 입력 str을 바이너리 값으로 변환합니다. fmt는 'hex', 'utf-8', 'utf8' 또는 'base64'의 대소문자를 구분하지 않는 문자열 리터럴일 수 있습니다. 기본적으로 변환을 위한 바이너리 형식은 fmt가 생략된 경우 'hex'입니다. 입력 파라미터 중 하나 이상이 NULL인 경우 함수는 NULL을 반환합니다. | 
| to\$1char(numberExpr, formatExpr) | formatExpr에 따라 numberExpr을 문자열로 변환합니다. 변환이 실패할 경우 예외가 발생합니다. 형식은 대소문자를 구분하지 않는 다음 문자로 구성됩니다. '0' 또는 '9': 0에서 9 사이의 예상 숫자를 지정합니다. 형식 문자열의 시퀀스 0 또는 9는 입력 값의 숫자 시퀀스와 일치하며, 형식 문자열의 해당 시퀀스와 동일한 길이의 결과 문자열을 생성합니다. 0/9 시퀀스가 10진수 값의 일치하는 부분보다 많은 숫자를 포함하고, 0으로 시작하고, 10진수 앞에 있는 경우 결과 문자열은 0으로 왼쪽 패딩됩니다. 그렇지 않으면 공백으로 채워집니다. '.' 또는 'D': 소수점의 위치를 지정합니다(선택 사항, 한 번만 허용). ',' 또는 'G': 그룹화(1,000) 구분 기호(,)의 위치를 지정합니다. 각 그룹화 구분 기호의 왼쪽과 오른쪽에 0 또는 9가 있어야 합니다. ' | 
| to\$1number(expr, fmt) | 문자열 형식 'fmt'에 따라 문자열 'expr'을 숫자로 변환합니다. 변환이 실패할 경우 예외가 발생합니다. 형식은 대소문자를 구분하지 않는 다음 문자로 구성됩니다. '0' 또는 '9': 0에서 9 사이의 예상 숫자를 지정합니다. 형식 문자열의 시퀀스 0 또는 9는 입력 문자열의 숫자 시퀀스와 일치합니다. 0/9 시퀀스가 0으로 시작하고 소수점 앞에 있는 경우 동일한 크기의 숫자 시퀀스만 매칭할 수 있습니다. 그렇지 않으면 시퀀스가 9로 시작하거나 소수점 뒤에 있는 경우 크기가 같거나 작은 숫자 시퀀스와 매칭할 수 있습니다. '.' 또는 'D': 소수점의 위치를 지정합니다(선택 사항, 한 번만 허용). ',' 또는 'G': 그룹화(1,000) 구분 기호(,)의 위치를 지정합니다. 각 그룹화 구분 기호의 왼쪽과 오른쪽에 0 또는 9가 있어야 합니다. 'expr'은 숫자 크기와 관련한 그룹화 구분 기호와 일치해야 합니다. ' | 
| to\$1varchar(numberExpr, formatExpr) | formatExpr에 따라 numberExpr을 문자열로 변환합니다. 변환이 실패할 경우 예외가 발생합니다. 형식은 대소문자를 구분하지 않는 다음 문자로 구성됩니다. '0' 또는 '9': 0에서 9 사이의 예상 숫자를 지정합니다. 형식 문자열의 시퀀스 0 또는 9는 입력 값의 숫자 시퀀스와 일치하며, 형식 문자열의 해당 시퀀스와 동일한 길이의 결과 문자열을 생성합니다. 0/9 시퀀스가 10진수 값의 일치하는 부분보다 많은 숫자를 포함하고, 0으로 시작하고, 10진수 앞에 있는 경우 결과 문자열은 0으로 왼쪽 패딩됩니다. 그렇지 않으면 공백으로 채워집니다. '.' 또는 'D': 소수점의 위치를 지정합니다(선택 사항, 한 번만 허용). ',' 또는 'G': 그룹화(1,000) 구분 기호(,)의 위치를 지정합니다. 각 그룹화 구분 기호의 왼쪽과 오른쪽에 0 또는 9가 있어야 합니다. ' | 
| translate(input, from, to) | from 문자열에 있는 문자를 to 문자열의 해당 문자로 대체함으로써 input 문자열을 변환합니다. | 
| trim(str) | str에서 선행 및 후행 공백 문자를 제거합니다. | 
| trim(BOTH FROM str) | str에서 선행 및 후행 공백 문자를 제거합니다. | 
| trim(LEADING FROM str) | str에서 선행 공백 문자를 제거합니다. | 
| trim(TRAILING FROM str) | str에서 후행 공백 문자를 제거합니다. | 
| trim(trimStr FROM str) | str에서 선행 및 후행 trimStr 문자를 제거합니다. | 
| trim(BOTH trimStr FROM str) | str에서 선행 및 후행 trimStr 문자를 제거합니다. | 
| trim(LEADING trimStr FROM str) | str에서 선행 trimStr 문자를 제거합니다. | 
| trim(TRAILING trimStr FROM str) | str에서 후행 trimStr 문자를 제거합니다. | 
| try\$1to\$1binary(str[, fmt]) | 동일한 작업을 수행하는 to\$1binary의 특수 버전이지만 변환을 수행할 수 없는 경우 오류를 발생시키는 대신 NULL 값을 반환합니다. | 
| try\$1to\$1number(expr, fmt) | 문자열 형식 fmt에 따라 문자열 'expr'을 숫자로 변환합니다. 문자열 'expr'이 예상 형식과 일치하지 않으면 NULL을 반환합니다. 형식은 to\$1number 함수와 동일한 의미 체계를 따릅니다. | 
| ucase(str) | 모든 문자가 대문자로 변경된 상태로 str을 반환합니다. | 
| unbase64(str) | 인수를 base 64 문자열 str에서 바이너리로 변환합니다. | 
| upper(str) | 모든 문자가 대문자로 변경된 상태로 str을 반환합니다. | 



**예시**

```
-- ascii
SELECT ascii('222');
+----------+
|ascii(222)|
+----------+
|        50|
+----------+
SELECT ascii(2);
+--------+
|ascii(2)|
+--------+
|      50|
+--------+
-- base64
SELECT base64('Feathers');
+-----------------+
|base64(Feathers)|
+-----------------+
|     RmVhdGhlcnM=|
+-----------------+
SELECT base64(x'537061726b2053514c');
+-----------------------------+
|base64(X'537061726B2053514C')|
+-----------------------------+
|                 U3BhcmsgU1FM|
+-----------------------------+
-- bit_length
SELECT bit_length('Feathers');
+---------------------+
|bit_length(Feathers)|
+---------------------+
|                   64|
+---------------------+
SELECT bit_length(x'537061726b2053514c');
+---------------------------------+
|bit_length(X'537061726B2053514C')|
+---------------------------------+
|                               72|
+---------------------------------+
-- btrim
SELECT btrim('    Feathers   ');
+----------------------+
|btrim(    Feathers   )|
+----------------------+
|              Feathers|
+----------------------+
SELECT btrim(encode('    Feathers   ', 'utf-8'));
+-------------------------------------+
|btrim(encode(    Feathers   , utf-8))|
+-------------------------------------+
|                             Feathers|
+-------------------------------------+
SELECT btrim('Feathers', 'Fe');
+---------------------+
|btrim(Alphabet, Al)|
+---------------------+
|               athers|
+---------------------+
SELECT btrim(encode('Feathers', 'utf-8'), encode('Al', 'utf-8'));
+---------------------------------------------------+
|btrim(encode(Feathers, utf-8), encode(Al, utf-8))|
+---------------------------------------------------+
|                                             athers|
+---------------------------------------------------+
-- char
SELECT char(65);
+--------+
|char(65)|
+--------+
|       A|
+--------+
-- char_length
SELECT char_length('Feathers ');
+-----------------------+
|char_length(Feathers )|
+-----------------------+
|                     9 |
+-----------------------+
SELECT char_length(x'537061726b2053514c');
+----------------------------------+
|char_length(X'537061726B2053514C')|
+----------------------------------+
|                                 9|
+----------------------------------+
SELECT CHAR_LENGTH('Feathers ');
+-----------------------+
|char_length(Feathers )|
+-----------------------+
|                     9|
+-----------------------+
SELECT CHARACTER_LENGTH('Feathers ');
+----------------------------+
|character_length(Feathers )|
+----------------------------+
|                          9|
+----------------------------+
-- character_length
SELECT character_length('Feathers ');
+----------------------------+
|character_length(Feathers )|
+----------------------------+
|                          9|
+----------------------------+
SELECT character_length(x'537061726b2053514c');
+---------------------------------------+
|character_length(X'537061726B2053514C')|
+---------------------------------------+
|                                      9|
+---------------------------------------+
SELECT CHAR_LENGTH('Feathers ');
+-----------------------+
|char_length(Feathers )|
+-----------------------+
|                     9|
+-----------------------+
SELECT CHARACTER_LENGTH('Feathers ');
+----------------------------+
|character_length(Feathers )|
+----------------------------+
|                          9|
+----------------------------+
-- chr
SELECT chr(65);
+-------+
|chr(65)|
+-------+
|      A|
+-------+
-- concat_ws
SELECT concat_ws(' ', 'Fea', 'thers');
+------------------------+
|concat_ws( , Fea, thers)|
+------------------------+
|               Feathers|
+------------------------+
SELECT concat_ws('s');
+------------+
|concat_ws(s)|
+------------+
|            |
+------------+
SELECT concat_ws('/', 'foo', null, 'bar');
+----------------------------+
|concat_ws(/, foo, NULL, bar)|
+----------------------------+
|                     foo/bar|
+----------------------------+
SELECT concat_ws(null, 'Fea', 'thers');
+---------------------------+
|concat_ws(NULL, Fea, thers)|
+---------------------------+
|                       NULL|
+---------------------------+
-- contains
SELECT contains('Feathers', 'Fea');
+--------------------------+
|contains(Feathers, Fea)|
+--------------------------+
|                      true|
+--------------------------+
SELECT contains('Feathers', 'SQL');
+--------------------------+
|contains(Feathers, SQL)|
+--------------------------+
|                     false|
+--------------------------+
SELECT contains('Feathers', null);
+-------------------------+
|contains(Feathers, NULL)|
+-------------------------+
|                     NULL|
+-------------------------+
SELECT contains(x'537061726b2053514c', x'537061726b');
+----------------------------------------------+
|contains(X'537061726B2053514C', X'537061726B')|
+----------------------------------------------+
|                                          true|
+----------------------------------------------+
-- decode
SELECT decode(encode('abc', 'utf-8'), 'utf-8');
+---------------------------------+
|decode(encode(abc, utf-8), utf-8)|
+---------------------------------+
|                              abc|
+---------------------------------+
SELECT decode(2, 1, 'Southlake', 2, 'San Francisco', 3, 'New Jersey', 4, 'Seattle', 'Non domestic');
+----------------------------------------------------------------------------------+
|decode(2, 1, Southlake, 2, San Francisco, 3, New Jersey, 4, Seattle, Non domestic)|
+----------------------------------------------------------------------------------+
|                                                                     San Francisco|
+----------------------------------------------------------------------------------+
SELECT decode(6, 1, 'Southlake', 2, 'San Francisco', 3, 'New Jersey', 4, 'Seattle', 'Non domestic');
+----------------------------------------------------------------------------------+
|decode(6, 1, Southlake, 2, San Francisco, 3, New Jersey, 4, Seattle, Non domestic)|
+----------------------------------------------------------------------------------+
|                                                                      Non domestic|
+----------------------------------------------------------------------------------+
SELECT decode(6, 1, 'Southlake', 2, 'San Francisco', 3, 'New Jersey', 4, 'Seattle');
+--------------------------------------------------------------------+
|decode(6, 1, Southlake, 2, San Francisco, 3, New Jersey, 4, Seattle)|
+--------------------------------------------------------------------+
|                                                                NULL|
+--------------------------------------------------------------------+
SELECT decode(null, 6, 'Fea', NULL, 'thers', 4, 'rock');
+-------------------------------------------+
|decode(NULL, 6, Fea, NULL, thers, 4, rock)|
+-------------------------------------------+
|                                      thers|
+-------------------------------------------+
-- elt
SELECT elt(1, 'scala', 'java');
+-------------------+
|elt(1, scala, java)|
+-------------------+
|              scala|
+-------------------+
SELECT elt(2, 'a', 1);
+------------+
|elt(2, a, 1)|
+------------+
|           1|
+------------+
-- encode
SELECT encode('abc', 'utf-8');
+------------------+
|encode(abc, utf-8)|
+------------------+
|        [61 62 63]|
+------------------+
-- endswith
SELECT endswith('Feathers', 'ers');
+------------------------+
|endswith(Feathers, ers)|
+------------------------+
|                    true|
+------------------------+
SELECT endswith('Feathers', 'SQL');
+--------------------------+
|endswith(Feathers, SQL)|
+--------------------------+
|                     false|
+--------------------------+
SELECT endswith('Feathers', null);
+-------------------------+
|endswith(Feathers, NULL)|
+-------------------------+
|                     NULL|
+-------------------------+
SELECT endswith(x'537061726b2053514c', x'537061726b');
+----------------------------------------------+
|endswith(X'537061726B2053514C', X'537061726B')|
+----------------------------------------------+
|                                         false|
+----------------------------------------------+
SELECT endswith(x'537061726b2053514c', x'53514c');
+------------------------------------------+
|endswith(X'537061726B2053514C', X'53514C')|
+------------------------------------------+
|                                      true|
+------------------------------------------+
-- find_in_set
SELECT find_in_set('ab','abc,b,ab,c,def');
+-------------------------------+
|find_in_set(ab, abc,b,ab,c,def)|
+-------------------------------+
|                              3|
+-------------------------------+
-- format_number
SELECT format_number(12332.123456, 4);
+------------------------------+
|format_number(12332.123456, 4)|
+------------------------------+
|                   12,332.1235|
+------------------------------+
SELECT format_number(12332.123456, '##################.###');
+---------------------------------------------------+
|format_number(12332.123456, ##################.###)|
+---------------------------------------------------+
|                                          12332.123|
+---------------------------------------------------+
-- format_string
SELECT format_string("Hello World %d %s", 100, "days");
+-------------------------------------------+
|format_string(Hello World %d %s, 100, days)|
+-------------------------------------------+
|                       Hello World 100 days|
+-------------------------------------------+
-- initcap
SELECT initcap('Feathers');
+------------------+
|initcap(Feathers)|
+------------------+
|         Feathers|
+------------------+
-- instr
SELECT instr('Feathers', 'ers');
+--------------------+
|instr(Feathers, ers)|
+--------------------+
|                   6|
+--------------------+
-- lcase
SELECT lcase('Feathers');
+---------------+
|lcase(Feathers)|
+---------------+
|       feathers|
+---------------+
-- left
SELECT left('Feathers', 3);
+------------------+
|left(Feathers, 3)|
+------------------+
|               Fea|
+------------------+
SELECT left(encode('Feathers', 'utf-8'), 3);
+---------------------------------+
|left(encode(Feathers, utf-8), 3)|
+---------------------------------+
|                       [RmVh]|
+---------------------------------+
-- len
SELECT len('Feathers ');
+---------------+
|len(Feathers )|
+---------------+
|             9|
+---------------+
SELECT len(x'537061726b2053514c');
+--------------------------+
|len(X'537061726B2053514C')|
+--------------------------+
|                         9|
+--------------------------+
SELECT CHAR_LENGTH('Feathers ');
+-----------------------+
|char_length(Feathers )|
+-----------------------+
|                     9|
+-----------------------+
SELECT CHARACTER_LENGTH('Feathers ');
+----------------------------+
|character_length(Feathers )|
+----------------------------+
|                          9|
+----------------------------+
-- length
SELECT length('Feathers ');
+------------------+
|length(Feathers )|
+------------------+
|                9|
+------------------+
SELECT length(x'537061726b2053514c');
+-----------------------------+
|length(X'537061726B2053514C')|
+-----------------------------+
|                            9|
+-----------------------------+
SELECT CHAR_LENGTH('Feathers ');
+-----------------------+
|char_length(Feathers )|
+-----------------------+
|                     9|
+-----------------------+
SELECT CHARACTER_LENGTH('Feathers ');
+----------------------------+
|character_length(Feathers )|
+----------------------------+
|                          9|
+----------------------------+
-- levenshtein
SELECT levenshtein('kitten', 'sitting');
+----------------------------+
|levenshtein(kitten, sitting)|
+----------------------------+
|                           3|
+----------------------------+
SELECT levenshtein('kitten', 'sitting', 2);
+-------------------------------+
|levenshtein(kitten, sitting, 2)|
+-------------------------------+
|                             -1|
+-------------------------------+
-- locate
SELECT locate('bar', 'foobarbar');
+-------------------------+
|locate(bar, foobarbar, 1)|
+-------------------------+
|                        4|
+-------------------------+
SELECT locate('bar', 'foobarbar', 5);
+-------------------------+
|locate(bar, foobarbar, 5)|
+-------------------------+
|                        7|
+-------------------------+
SELECT POSITION('bar' IN 'foobarbar');
+-------------------------+
|locate(bar, foobarbar, 1)|
+-------------------------+
|                        4|
+-------------------------+
-- lower
SELECT lower('Feathers');
+---------------+
|lower(Feathers)|
+---------------+
|       feathers|
+---------------+
-- lpad
SELECT lpad('hi', 5, '??');
+---------------+
|lpad(hi, 5, ??)|
+---------------+
|          ???hi|
+---------------+
SELECT lpad('hi', 1, '??');
+---------------+
|lpad(hi, 1, ??)|
+---------------+
|              h|
+---------------+
SELECT lpad('hi', 5);
+--------------+
|lpad(hi, 5,  )|
+--------------+
|            hi|
+--------------+
SELECT hex(lpad(unhex('aabb'), 5));
+--------------------------------+
|hex(lpad(unhex(aabb), 5, X'00'))|
+--------------------------------+
|                      000000AABB|
+--------------------------------+
SELECT hex(lpad(unhex('aabb'), 5, unhex('1122')));
+--------------------------------------+
|hex(lpad(unhex(aabb), 5, unhex(1122)))|
+--------------------------------------+
|                            112211AABB|
+--------------------------------------+
-- ltrim
SELECT ltrim('    Feathers   ');
+----------------------+
|ltrim(    Feathers   )|
+----------------------+
|           Feathers   |
+----------------------+
-- luhn_check
SELECT luhn_check('8112189876');
+----------------------+
|luhn_check(8112189876)|
+----------------------+
|                  true|
+----------------------+
SELECT luhn_check('79927398713');
+-----------------------+
|luhn_check(79927398713)|
+-----------------------+
|                   true|
+-----------------------+
SELECT luhn_check('79927398714');
+-----------------------+
|luhn_check(79927398714)|
+-----------------------+
|                  false|
+-----------------------+
-- mask
SELECT mask('abcd-EFGH-8765-4321');
+----------------------------------------+
|mask(abcd-EFGH-8765-4321, X, x, n, NULL)|
+----------------------------------------+
|                     xxxx-XXXX-nnnn-nnnn|
+----------------------------------------+
SELECT mask('abcd-EFGH-8765-4321', 'Q');
+----------------------------------------+
|mask(abcd-EFGH-8765-4321, Q, x, n, NULL)|
+----------------------------------------+
|                     xxxx-QQQQ-nnnn-nnnn|
+----------------------------------------+
SELECT mask('AbCD123-@$#', 'Q', 'q');
+--------------------------------+
|mask(AbCD123-@$#, Q, q, n, NULL)|
+--------------------------------+
|                     QqQQnnn-@$#|
+--------------------------------+
SELECT mask('AbCD123-@$#');
+--------------------------------+
|mask(AbCD123-@$#, X, x, n, NULL)|
+--------------------------------+
|                     XxXXnnn-@$#|
+--------------------------------+
SELECT mask('AbCD123-@$#', 'Q');
+--------------------------------+
|mask(AbCD123-@$#, Q, x, n, NULL)|
+--------------------------------+
|                     QxQQnnn-@$#|
+--------------------------------+
SELECT mask('AbCD123-@$#', 'Q', 'q');
+--------------------------------+
|mask(AbCD123-@$#, Q, q, n, NULL)|
+--------------------------------+
|                     QqQQnnn-@$#|
+--------------------------------+
SELECT mask('AbCD123-@$#', 'Q', 'q', 'd');
+--------------------------------+
|mask(AbCD123-@$#, Q, q, d, NULL)|
+--------------------------------+
|                     QqQQddd-@$#|
+--------------------------------+
SELECT mask('AbCD123-@$#', 'Q', 'q', 'd', 'o');
+-----------------------------+
|mask(AbCD123-@$#, Q, q, d, o)|
+-----------------------------+
|                  QqQQdddoooo|
+-----------------------------+
SELECT mask('AbCD123-@$#', NULL, 'q', 'd', 'o');
+--------------------------------+
|mask(AbCD123-@$#, NULL, q, d, o)|
+--------------------------------+
|                     AqCDdddoooo|
+--------------------------------+
SELECT mask('AbCD123-@$#', NULL, NULL, 'd', 'o');
+-----------------------------------+
|mask(AbCD123-@$#, NULL, NULL, d, o)|
+-----------------------------------+
|                        AbCDdddoooo|
+-----------------------------------+
SELECT mask('AbCD123-@$#', NULL, NULL, NULL, 'o');
+--------------------------------------+
|mask(AbCD123-@$#, NULL, NULL, NULL, o)|
+--------------------------------------+
|                           AbCD123oooo|
+--------------------------------------+
SELECT mask(NULL, NULL, NULL, NULL, 'o');
+-------------------------------+
|mask(NULL, NULL, NULL, NULL, o)|
+-------------------------------+
|                           NULL|
+-------------------------------+
SELECT mask(NULL);
+-------------------------+
|mask(NULL, X, x, n, NULL)|
+-------------------------+
|                     NULL|
+-------------------------+
SELECT mask('AbCD123-@$#', NULL, NULL, NULL, NULL);
+-----------------------------------------+
|mask(AbCD123-@$#, NULL, NULL, NULL, NULL)|
+-----------------------------------------+
|                              AbCD123-@$#|
+-----------------------------------------+
-- octet_length
SELECT octet_length('Feathers');
+-----------------------+
|octet_length(Feathers)|
+-----------------------+
|                      8|
+-----------------------+
SELECT octet_length(x'537061726b2053514c');
+-----------------------------------+
|octet_length(X'537061726B2053514C')|
+-----------------------------------+
|                                  9|
+-----------------------------------+
-- overlay
SELECT overlay('Feathers' PLACING '_' FROM 6);
+----------------------------+
|overlay(Feathers, _, 6, -1)|
+----------------------------+
|                   Feathe_ers|
+----------------------------+
SELECT overlay('Feathers' PLACING 'ures' FROM 5);
+-------------------------------+
|overlay(Feathers, ures, 5, -1)|
+-------------------------------+
|                     Features  |
+-------------------------------+
-- position
SELECT position('bar', 'foobarbar');
+---------------------------+
|position(bar, foobarbar, 1)|
+---------------------------+
|                          4|
+---------------------------+
SELECT position('bar', 'foobarbar', 5);
+---------------------------+
|position(bar, foobarbar, 5)|
+---------------------------+
|                          7|
+---------------------------+
SELECT POSITION('bar' IN 'foobarbar');
+-------------------------+
|locate(bar, foobarbar, 1)|
+-------------------------+
|                        4|
+-------------------------+
-- printf
SELECT printf("Hello World %d %s", 100, "days");
+------------------------------------+
|printf(Hello World %d %s, 100, days)|
+------------------------------------+
|                Hello World 100 days|
+------------------------------------+
-- regexp_count
SELECT regexp_count('Steven Jones and Stephen Smith are the best players', 'Ste(v|ph)en');
+------------------------------------------------------------------------------+
|regexp_count(Steven Jones and Stephen Smith are the best players, Ste(v|ph)en)|
+------------------------------------------------------------------------------+
|                                                                             2|
+------------------------------------------------------------------------------+
SELECT regexp_count('abcdefghijklmnopqrstuvwxyz', '[a-z]{3}');
+--------------------------------------------------+
|regexp_count(abcdefghijklmnopqrstuvwxyz, [a-z]{3})|
+--------------------------------------------------+
|                                                 8|
+--------------------------------------------------+
-- regexp_extract
SELECT regexp_extract('100-200', '(\\d+)-(\\d+)', 1);
+---------------------------------------+
|regexp_extract(100-200, (\d+)-(\d+), 1)|
+---------------------------------------+
|                                    100|
+---------------------------------------+
-- regexp_extract_all
SELECT regexp_extract_all('100-200, 300-400', '(\\d+)-(\\d+)', 1);
+----------------------------------------------------+
|regexp_extract_all(100-200, 300-400, (\d+)-(\d+), 1)|
+----------------------------------------------------+
|                                          [100, 300]|
+----------------------------------------------------+
-- regexp_instr
SELECT regexp_instr('user@opensearch.org', '@[^.]*');
+----------------------------------------------+
|regexp_instr(user@opensearch.org, @[^.]*, 0)|
+----------------------------------------------+
|                                             5|
+----------------------------------------------+
-- regexp_replace
SELECT regexp_replace('100-200', '(\\d+)', 'num');
+--------------------------------------+
|regexp_replace(100-200, (\d+), num, 1)|
+--------------------------------------+
|                               num-num|
+--------------------------------------+
-- regexp_substr
SELECT regexp_substr('Steven Jones and Stephen Smith are the best players', 'Ste(v|ph)en');
+-------------------------------------------------------------------------------+
|regexp_substr(Steven Jones and Stephen Smith are the best players, Ste(v|ph)en)|
+-------------------------------------------------------------------------------+
|                                                                         Steven|
+-------------------------------------------------------------------------------+
SELECT regexp_substr('Steven Jones and Stephen Smith are the best players', 'Jeck');
+------------------------------------------------------------------------+
|regexp_substr(Steven Jones and Stephen Smith are the best players, Jeck)|
+------------------------------------------------------------------------+
|                                                                    NULL|
+------------------------------------------------------------------------+
-- repeat
SELECT repeat('123', 2);
+--------------+
|repeat(123, 2)|
+--------------+
|        123123|
+--------------+
-- replace
SELECT replace('ABCabc', 'abc', 'DEF');
+-------------------------+
|replace(ABCabc, abc, DEF)|
+-------------------------+
|                   ABCDEF|
+-------------------------+
-- right
SELECT right('Feathers', 3);
+-------------------+
|right(Feathers, 3)|
+-------------------+
|                ers|
+-------------------+
-- rpad
SELECT rpad('hi', 5, '??');
+---------------+
|rpad(hi, 5, ??)|
+---------------+
|          hi???|
+---------------+
SELECT rpad('hi', 1, '??');
+---------------+
|rpad(hi, 1, ??)|
+---------------+
|              h|
+---------------+
SELECT rpad('hi', 5);
+--------------+
|rpad(hi, 5,  )|
+--------------+
|         hi   |
+--------------+
SELECT hex(rpad(unhex('aabb'), 5));
+--------------------------------+
|hex(rpad(unhex(aabb), 5, X'00'))|
+--------------------------------+
|                      AABB000000|
+--------------------------------+
SELECT hex(rpad(unhex('aabb'), 5, unhex('1122')));
+--------------------------------------+
|hex(rpad(unhex(aabb), 5, unhex(1122)))|
+--------------------------------------+
|                            AABB112211|
+--------------------------------------+
-- rtrim
SELECT rtrim('    Feathers   ');
+----------------------+
|rtrim(    Feathers   )|
+----------------------+
|              Feathers|
+----------------------+
-- sentences
SELECT sentences('Hi there! Good morning.');
+--------------------------------------+
|sentences(Hi there! Good morning., , )|
+--------------------------------------+
|                  [[Hi, there], [Go...|
+--------------------------------------+
-- soundex
SELECT soundex('Miller');
+---------------+
|soundex(Miller)|
+---------------+
|           M460|
+---------------+
-- space
SELECT concat(space(2), '1');
+-------------------+
|concat(space(2), 1)|
+-------------------+
|                  1|
+-------------------+
-- split
SELECT split('oneAtwoBthreeC', '[ABC]');
+--------------------------------+
|split(oneAtwoBthreeC, [ABC], -1)|
+--------------------------------+
|             [one, two, three, ]|
+--------------------------------+
SELECT split('oneAtwoBthreeC', '[ABC]', -1);
+--------------------------------+
|split(oneAtwoBthreeC, [ABC], -1)|
+--------------------------------+
|             [one, two, three, ]|
+--------------------------------+
SELECT split('oneAtwoBthreeC', '[ABC]', 2);
+-------------------------------+
|split(oneAtwoBthreeC, [ABC], 2)|
+-------------------------------+
|              [one, twoBthreeC]|
+-------------------------------+
-- split_part
SELECT split_part('11.12.13', '.', 3);
+--------------------------+
|split_part(11.12.13, ., 3)|
+--------------------------+
|                        13|
+--------------------------+
-- startswith
SELECT startswith('Feathers', 'Fea');
+----------------------------+
|startswith(Feathers, Fea)|
+----------------------------+
|                        true|
+----------------------------+
SELECT startswith('Feathers', 'SQL');
+--------------------------+
|startswith(Feathers, SQL)|
+--------------------------+
|                     false|
+--------------------------+
SELECT startswith('Feathers', null);
+---------------------------+
|startswith(Feathers, NULL)|
+---------------------------+
|                       NULL|
+---------------------------+
SELECT startswith(x'537061726b2053514c', x'537061726b');
+------------------------------------------------+
|startswith(X'537061726B2053514C', X'537061726B')|
+------------------------------------------------+
|                                            true|
+------------------------------------------------+
SELECT startswith(x'537061726b2053514c', x'53514c');
+--------------------------------------------+
|startswith(X'537061726B2053514C', X'53514C')|
+--------------------------------------------+
|                                       false|
+--------------------------------------------+
-- substr
SELECT substr('Feathers', 5);
+--------------------------------+
|substr(Feathers, 5, 2147483647)|
+--------------------------------+
|                           hers |
+--------------------------------+
SELECT substr('Feathers', -3);
+---------------------------------+
|substr(Feathers, -3, 2147483647)|
+---------------------------------+
|                              ers|
+---------------------------------+
SELECT substr('Feathers', 5, 1);
+-----------------------+
|substr(Feathers, 5, 1)|
+-----------------------+
|                      h|
+-----------------------+
SELECT substr('Feathers' FROM 5);
+-----------------------------------+
|substring(Feathers, 5, 2147483647)|
+-----------------------------------+
|                              hers |
+-----------------------------------+
SELECT substr('Feathers' FROM -3);
+------------------------------------+
|substring(Feathers, -3, 2147483647)|
+------------------------------------+
|                                 ers|
+------------------------------------+
SELECT substr('Feathers' FROM 5 FOR 1);
+--------------------------+
|substring(Feathers, 5, 1)|
+--------------------------+
|                         h|
+--------------------------+
-- substring
SELECT substring('Feathers', 5);
+-----------------------------------+
|substring(Feathers, 5, 2147483647)|
+-----------------------------------+
|                              hers |
+-----------------------------------+
SELECT substring('Feathers', -3);
+------------------------------------+
|substring(Feathers, -3, 2147483647)|
+------------------------------------+
|                                 ers|
+------------------------------------+
SELECT substring('Feathers', 5, 1);
+--------------------------+
|substring(Feathers, 5, 1)|
+--------------------------+
|                         h|
+--------------------------+
SELECT substring('Feathers' FROM 5);
+-----------------------------------+
|substring(Feathers, 5, 2147483647)|
+-----------------------------------+
|                              hers |
+-----------------------------------+
SELECT substring('Feathers' FROM -3);
+------------------------------------+
|substring(Feathers, -3, 2147483647)|
+------------------------------------+
|                                 ers|
+------------------------------------+
SELECT substring('Feathers' FROM 5 FOR 1);
+--------------------------+
|substring(Feathers, 5, 1)|
+--------------------------+
|                         h|
+--------------------------+
-- substring_index
SELECT substring_index('www.apache.org', '.', 2);
+-------------------------------------+
|substring_index(www.apache.org, ., 2)|
+-------------------------------------+
|                           www.apache|
+-------------------------------------+
-- to_binary
SELECT to_binary('abc', 'utf-8');
+---------------------+
|to_binary(abc, utf-8)|
+---------------------+
|           [61 62 63]|
+---------------------+
-- to_char
SELECT to_char(454, '999');
+-----------------+
|to_char(454, 999)|
+-----------------+
|              454|
+-----------------+
SELECT to_char(454.00, '000D00');
+-----------------------+
|to_char(454.00, 000D00)|
+-----------------------+
|                 454.00|
+-----------------------+
SELECT to_char(12454, '99G999');
+----------------------+
|to_char(12454, 99G999)|
+----------------------+
|                12,454|
+----------------------+
SELECT to_char(78.12, '$99.99');
+----------------------+
|to_char(78.12, $99.99)|
+----------------------+
|                $78.12|
+----------------------+
SELECT to_char(-12454.8, '99G999D9S');
+----------------------------+
|to_char(-12454.8, 99G999D9S)|
+----------------------------+
|                   12,454.8-|
+----------------------------+
-- to_number
SELECT to_number('454', '999');
+-------------------+
|to_number(454, 999)|
+-------------------+
|                454|
+-------------------+
SELECT to_number('454.00', '000.00');
+-------------------------+
|to_number(454.00, 000.00)|
+-------------------------+
|                   454.00|
+-------------------------+
SELECT to_number('12,454', '99,999');
+-------------------------+
|to_number(12,454, 99,999)|
+-------------------------+
|                    12454|
+-------------------------+
SELECT to_number('$78.12', '$99.99');
+-------------------------+
|to_number($78.12, $99.99)|
+-------------------------+
|                    78.12|
+-------------------------+
SELECT to_number('12,454.8-', '99,999.9S');
+-------------------------------+
|to_number(12,454.8-, 99,999.9S)|
+-------------------------------+
|                       -12454.8|
+-------------------------------+
-- to_varchar
SELECT to_varchar(454, '999');
+-----------------+
|to_char(454, 999)|
+-----------------+
|              454|
+-----------------+
SELECT to_varchar(454.00, '000D00');
+-----------------------+
|to_char(454.00, 000D00)|
+-----------------------+
|                 454.00|
+-----------------------+
SELECT to_varchar(12454, '99G999');
+----------------------+
|to_char(12454, 99G999)|
+----------------------+
|                12,454|
+----------------------+
SELECT to_varchar(78.12, '$99.99');
+----------------------+
|to_char(78.12, $99.99)|
+----------------------+
|                $78.12|
+----------------------+
SELECT to_varchar(-12454.8, '99G999D9S');
+----------------------------+
|to_char(-12454.8, 99G999D9S)|
+----------------------------+
|                   12,454.8-|
+----------------------------+
-- translate
SELECT translate('AaBbCc', 'abc', '123');
+---------------------------+
|translate(AaBbCc, abc, 123)|
+---------------------------+
|                     A1B2C3|
+---------------------------+
-- try_to_binary
SELECT try_to_binary('abc', 'utf-8');
+-------------------------+
|try_to_binary(abc, utf-8)|
+-------------------------+
|               [61 62 63]|
+-------------------------+
select try_to_binary('a!', 'base64');
+-------------------------+
|try_to_binary(a!, base64)|
+-------------------------+
|                     NULL|
+-------------------------+
select try_to_binary('abc', 'invalidFormat');
+---------------------------------+
|try_to_binary(abc, invalidFormat)|
+---------------------------------+
|                             NULL|
+---------------------------------+
-- try_to_number
SELECT try_to_number('454', '999');
+-----------------------+
|try_to_number(454, 999)|
+-----------------------+
|                    454|
+-----------------------+
SELECT try_to_number('454.00', '000.00');
+-----------------------------+
|try_to_number(454.00, 000.00)|
+-----------------------------+
|                       454.00|
+-----------------------------+
SELECT try_to_number('12,454', '99,999');
+-----------------------------+
|try_to_number(12,454, 99,999)|
+-----------------------------+
|                        12454|
+-----------------------------+
SELECT try_to_number('$78.12', '$99.99');
+-----------------------------+
|try_to_number($78.12, $99.99)|
+-----------------------------+
|                        78.12|
+-----------------------------+
SELECT try_to_number('12,454.8-', '99,999.9S');
+-----------------------------------+
|try_to_number(12,454.8-, 99,999.9S)|
+-----------------------------------+
|                           -12454.8|
+-----------------------------------+
-- ucase
SELECT ucase('Feathers');
+---------------+
|ucase(Feathers)|
+---------------+
|       FEATHERS|
+---------------+
-- unbase64
SELECT unbase64('U3BhcmsgU1FM');
+----------------------+
|unbase64(U3BhcmsgU1FM)|
+----------------------+
|  [53 70 61 72 6B 2...|
+----------------------+
-- upper
SELECT upper('Feathers');
+---------------+
|upper(Feathers)|
+---------------+
|       FEATHERS|
+---------------+
```

#### 날짜 및 시간 함수
<a name="supported-sql-date-time"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).


****  

| 함수 | 설명 | 
| --- | --- | 
| add\$1months(start\$1date, num\$1months) | start\$1date로부터 num\$1months 후 날짜를 반환합니다. | 
| convert\$1timezone([sourceTz, ]targetTz, sourceTs) | 시간대가 없는 타임스탬프 sourceTz를 시간대 sourceTs에서 targetTz로 변환합니다. | 
| curdate() | 쿼리 평가 시작 시 현재 날짜를 반환합니다. 동일한 쿼리 내의 모든 curdate 호출은 동일한 값을 반환합니다. | 
| current\$1date() | 쿼리 평가 시작 시 현재 날짜를 반환합니다. 동일한 쿼리 내의 모든 current\$1date 호출은 동일한 값을 반환합니다. | 
| current\$1date | 쿼리 평가 시작 시 현재 날짜를 반환합니다. | 
| current\$1timestamp() | 쿼리 평가 시작 시 현재 타임스탬프를 반환합니다. 동일한 쿼리 내의 모든 current\$1timestamp 호출은 동일한 값을 반환합니다. | 
| current\$1timestamp | 쿼리 평가 시작 시 현재 타임스탬프를 반환합니다. | 
| current\$1timezone() | 현재 세션의 현지 시간대를 반환합니다. | 
| date\$1add(start\$1date, num\$1days) | start\$1date로부터 num\$1days 후 날짜를 반환합니다. | 
| date\$1diff(endDate, startDate) | startDate에서 endDate까지의 일수를 반환합니다. | 
| date\$1format(timestamp, fmt) | 날짜 형식 fmt로 지정된 형식의 문자열 값으로 timestamp를 변환합니다. | 
| date\$1from\$1unix\$1date(days) | 1970-01-01 이후 일수에서 날짜를 생성합니다. | 
| date\$1part(field, source) | 날짜/타임스탬프 또는 간격 소스의 일부를 추출합니다. | 
| date\$1sub(start\$1date, num\$1days) | start\$1date로부터 num\$1days 전 날짜를 반환합니다. | 
| date\$1trunc(fmt, ts) | 형식 모델 fmt에서 지정한 단위로 잘린 타임스탬프 ts를 반환합니다. | 
| dateadd(start\$1date, num\$1days) | start\$1date로부터 num\$1days 후 날짜를 반환합니다. | 
| datediff(endDate, startDate) | startDate에서 endDate까지의 일수를 반환합니다. | 
| datepart(field, source) | 날짜/타임스탬프 또는 간격 소스의 일부를 추출합니다. | 
| day(date) | 날짜/타임스탬프의 요일을 반환합니다. | 
| dayofmonth(date) | 날짜/타임스탬프의 요일을 반환합니다. | 
| dayofweek(date) | 날짜/타임스탬프의 요일을 반환합니다(1 = 일요일, 2 = 월요일, ..., 7 = 토요일). | 
| dayofyear(date) | 날짜/타임스탬프의 날짜를 반환합니다. | 
| extract(field FROM source) | 날짜/타임스탬프 또는 간격 소스의 일부를 추출합니다. | 
| from\$1unixtime(unix\$1time[, fmt]) | 지정된 fmt에서 unix\$1time을 반환합니다. | 
| from\$1utc\$1timestamp(timestamp, timezone) | '2017-07-14 02:40:00.0'과 같은 타임스탬프가 주어지면, 이를 UTC의 시간으로 해석하고 해당 시간을 지정된 시간대의 타임스탬프로 렌더링합니다. 예를 들어 'GMT\$11'은 '2017-07-14 03:40:00.0'을 생성합니다. | 
| hour(timestamp) | 문자열/타임스탬프의 시간 구성 요소를 반환합니다. | 
| last\$1day(date) | 날짜가 속한 달의 마지막 날을 반환합니다. | 
| localtimestamp() | 쿼리 평가 시작 시 시간대가 없는 현재 타임스탬프를 반환합니다. 동일한 쿼리 내의 모든 localtimestamp 호출은 동일한 값을 반환합니다. | 
| localtimestamp | 쿼리 평가 시작 시 세션 시간대의 현재 로컬 날짜-시간을 반환합니다. | 
| make\$1date(year, month, day) | 연도, 월 및 일 필드에서 날짜를 생성합니다. | 
| make\$1dt\$1interval([days[, hours[, mins[, secs]]]]) | 일, 시간, 분 및 초에서 DayTimeIntervalType 기간을 만듭니다. | 
| make\$1interval([years[, months[, weeks[, days[, hours[, mins[, secs]]]]]]]) | 년, 월, 주, 일, 시간, 분 및 초에서 간격을 만듭니다. | 
| make\$1timestamp(year, month, day, hour, min, sec[, timezone]) | 연도, 월, 일, 시간, 분, 초 및 시간대 필드에서 타임스탬프를 생성합니다. | 
| make\$1timestamp\$1ltz(year, month, day, hour, min, sec[, timezone]) | 연도, 월, 일, 시간, 분, 초 및 시간대 필드의 현지 시간대로 현재 타임스탬프를 생성합니다. | 
| make\$1timestamp\$1ntz(year, month, day, hour, min, sec) | 년, 월, 일, 시간, 분, 초 필드에서 로컬 날짜-시간을 생성합니다. | 
| make\$1ym\$1interval([years[, months]]) | 년, 월에서 년-월 간격을 만듭니다. | 
| minute(timestamp) | 문자열/타임스탬프의 분 구성 요소를 반환합니다. | 
| month(date) | 날짜/타임스탬프의 월 구성 요소를 반환합니다. | 
| months\$1between(timestamp1, timestamp2[, roundOff]) | timestamp1이 timestamp2보다 이후인 경우 결과는 양수입니다. timestamp1 및 timestamp2가 같은 요일이거나 둘 다 마지막 요일인 경우 시간대는 무시됩니다. 그렇지 않으면 차이는 매월 31일을 기준으로 계산되며 roundOff=false가 아니면 8자리로 반올림됩니다. | 
| next\$1day(start\$1date, day\$1of\$1week) | 표시된 대로 start\$1date 이후이고 이름이 지정된 첫 번째 날짜를 반환합니다. 입력 파라미터 중 하나 이상이 NULL인 경우 함수는 NULL을 반환합니다. | 
| now() | 쿼리 평가 시작 시 현재 타임스탬프를 반환합니다. | 
| quarter(date) | 날짜의 분기를 1\$14 범위로 반환합니다. | 
| second(timestamp) | 문자열/타임스탬프의 초 구성 요소를 반환합니다. | 
| session\$1window(time\$1column, gap\$1duration) | 열 및 간격 기간을 지정하는 타임스탬프가 지정된 세션 윈도우를 생성합니다. 자세한 설명과 예는 구조화 스트리밍 가이드 문서의 '시간 범위 유형'을 참조하세요. | 
| timestamp\$1micros(microseconds) | UTC 에포크 이후 마이크로초 수에서 타임스탬프를 생성합니다. | 
| timestamp\$1millis(milliseconds) | UTC 에포크 이후 밀리초 수에서 타임스탬프를 생성합니다. | 
| timestamp\$1seconds(seconds) | UTC 에포크 이후 초(분수일 수 있음)에서 타임스탬프를 생성합니다. | 
| to\$1date(date\$1str[, fmt]) | date\$1str 표현식이 포함된 fmt 표현식을 날짜로 구문 분석합니다. 잘못된 입력 시 null을 반환합니다. 기본적으로 fmt가 생략된 경우 캐스팅 규칙을 따라 날짜를 지정합니다. | 
| to\$1timestamp(timestamp\$1str[, fmt]) | timestamp\$1str 표현식이 포함된 fmt 표현식을 타임스탬프로 구문 분석합니다. 잘못된 입력 시 null을 반환합니다. 기본적으로 fmt가 생략된 경우 캐스팅 규칙을 따라 타임스탬프를 지정합니다. | 
| to\$1timestamp\$1ltz(timestamp\$1str[, fmt]) | timestamp\$1str 표현식이 있는 fmt 표현식을 현지 시간대가 있는 타임스탬프로 구문 분석합니다. 잘못된 입력 시 null을 반환합니다. 기본적으로 fmt가 생략된 경우 캐스팅 규칙을 따라 타임스탬프를 지정합니다. | 
| to\$1timestamp\$1ntz(timestamp\$1str[, fmt]) | timestamp\$1str 표현식이 있는 fmt 표현식을 시간대가 없는 타임스탬프로 구문 분석합니다. 잘못된 입력 시 null을 반환합니다. 기본적으로 fmt가 생략된 경우 캐스팅 규칙을 따라 타임스탬프를 지정합니다. | 
| to\$1unix\$1timestamp(timeExp[, fmt]) | 지정된 시간의 UNIX 타임스탬프를 반환합니다. | 
| to\$1utc\$1timestamp(timestamp, timezone) | '2017-07-14 02:40:00.0'과 같은 타임스탬프가 주어지면, 이를 지정된 시간대의 시간으로 해석하고 해당 시간을 UTC의 타임스탬프로 렌더링합니다. 예를 들어 'GMT\$11'은 '2017-07-14 01:40:00.0'을 생성합니다. | 
| trunc(date, fmt) | 형식 모델 fmt에서 지정한 단위로 잘린 날짜의 시간 부분이 있는 date를 반환합니다. | 
| try\$1to\$1timestamp(timestamp\$1str[, fmt]) | timestamp\$1str 표현식이 포함된 fmt 표현식을 타임스탬프로 구문 분석합니다. | 
| unix\$1date(date) | 1970-01-01 이후 일수를 반환합니다. | 
| unix\$1micros(timestamp) | 1970-01-01 00:00:00 UTC 이후 마이크로초 수를 반환합니다. | 
| unix\$1millis(timestamp) | 1970-01-01 00:00:00 UTC 이후 밀리초 수를 반환합니다. 더 높은 수준의 정밀도를 자릅니다. | 
| unix\$1seconds(timestamp) | 1970-01-01 00:00:00 UTC 이후의 초 수를 반환합니다. 더 높은 수준의 정밀도를 자릅니다. | 
| unix\$1timestamp([timeExp[, fmt]]) | 현재 또는 지정된 시간의 UNIX 타임스탬프를 반환합니다. | 
| weekday(date) | 날짜/타임스탬프의 요일을 반환합니다(0 = 월요일, 1 = 화요일, ..., 6 = 일요일). | 
| weekofyear(date) | 지정된 날짜가 그 해 몇 주차인지 반환합니다. 한 주는 월요일에 시작하며, 1주는 3일을 초과하는 날이 포함된 첫 번째 주로 간주됩니다. | 
| window(time\$1column, window\$1duration[, slide\$1duration[, start\$1time]]) | 열을 지정하는 타임스탬프가 주어지면 행을 하나 이상의 윈도우로 버킷화합니다. 윈도우의 시작은 포함되지만 윈도우의 끝은 제외됩니다. 예를 들어 12:05는 [12:05,12:10) 기간에는 있지만 [12:00,12:05)에는 없습니다. 윈도우는 마이크로초 정밀도를 지원할 수 있습니다. 월 단위의 윈도우는 지원되지 않습니다. 자세한 설명과 예는 구조화 스트리밍 가이드 문서의 '이벤트 시간에 대한 윈도우 작업'을 참조하세요. | 
| window\$1time(window\$1column) | 윈도우의 이벤트 시간 값에 사용할 수 있는 시간/세션 기간 열에서 윈도우 값을 추출합니다. 추출된 시간은 (window.end - 1)이며, 이는 집계 윈도우에 배타적인 구간, 즉 [start, end)가 있다는 사실을 반영합니다. 자세한 설명과 예는 구조화 스트리밍 가이드 문서의 '이벤트 시간에 대한 윈도우 작업'을 참조하세요. | 
| year(date) | 날짜/타임스탬프의 연도 구성 요소를 반환합니다. | 

**예시**

```
-- add_months
SELECT add_months('2016-08-31', 1);
+-------------------------+
|add_months(2016-08-31, 1)|
+-------------------------+
|               2016-09-30|
+-------------------------+
-- convert_timezone
SELECT convert_timezone('Europe/Brussels', 'America/Los_Angeles', timestamp_ntz'2021-12-06 00:00:00');
+-------------------------------------------------------------------------------------------+
|convert_timezone(Europe/Brussels, America/Los_Angeles, TIMESTAMP_NTZ '2021-12-06 00:00:00')|
+-------------------------------------------------------------------------------------------+
|                                                                        2021-12-05 15:00:00|
+-------------------------------------------------------------------------------------------+
SELECT convert_timezone('Europe/Brussels', timestamp_ntz'2021-12-05 15:00:00');
+------------------------------------------------------------------------------------------+
|convert_timezone(current_timezone(), Europe/Brussels, TIMESTAMP_NTZ '2021-12-05 15:00:00')|
+------------------------------------------------------------------------------------------+
|                                                                       2021-12-05 07:00:00|
+------------------------------------------------------------------------------------------+
-- curdate
SELECT curdate();
+--------------+
|current_date()|
+--------------+
|    2024-02-24|
+--------------+
-- current_date
SELECT current_date();
+--------------+
|current_date()|
+--------------+
|    2024-02-24|
+--------------+
SELECT current_date;
+--------------+
|current_date()|
+--------------+
|    2024-02-24|
+--------------+
-- current_timestamp
SELECT current_timestamp();
+--------------------+
| current_timestamp()|
+--------------------+
|2024-02-24 16:36:...|
+--------------------+
SELECT current_timestamp;
+--------------------+
| current_timestamp()|
+--------------------+
|2024-02-24 16:36:...|
+--------------------+
-- current_timezone
SELECT current_timezone();
+------------------+
|current_timezone()|
+------------------+
|        Asia/Seoul|
+------------------+
-- date_add
SELECT date_add('2016-07-30', 1);
+-----------------------+
|date_add(2016-07-30, 1)|
+-----------------------+
|             2016-07-31|
+-----------------------+
-- date_diff
SELECT date_diff('2009-07-31', '2009-07-30');
+---------------------------------+
|date_diff(2009-07-31, 2009-07-30)|
+---------------------------------+
|                                1|
+---------------------------------+
SELECT date_diff('2009-07-30', '2009-07-31');
+---------------------------------+
|date_diff(2009-07-30, 2009-07-31)|
+---------------------------------+
|                               -1|
+---------------------------------+
-- date_format
SELECT date_format('2016-04-08', 'y');
+--------------------------+
|date_format(2016-04-08, y)|
+--------------------------+
|                      2016|
+--------------------------+
-- date_from_unix_date
SELECT date_from_unix_date(1);
+----------------------+
|date_from_unix_date(1)|
+----------------------+
|            1970-01-02|
+----------------------+
-- date_part
SELECT date_part('YEAR', TIMESTAMP '2019-08-12 01:00:00.123456');
+-------------------------------------------------------+
|date_part(YEAR, TIMESTAMP '2019-08-12 01:00:00.123456')|
+-------------------------------------------------------+
|                                                   2019|
+-------------------------------------------------------+
SELECT date_part('week', timestamp'2019-08-12 01:00:00.123456');
+-------------------------------------------------------+
|date_part(week, TIMESTAMP '2019-08-12 01:00:00.123456')|
+-------------------------------------------------------+
|                                                     33|
+-------------------------------------------------------+
SELECT date_part('doy', DATE'2019-08-12');
+---------------------------------+
|date_part(doy, DATE '2019-08-12')|
+---------------------------------+
|                              224|
+---------------------------------+
SELECT date_part('SECONDS', timestamp'2019-10-01 00:00:01.000001');
+----------------------------------------------------------+
|date_part(SECONDS, TIMESTAMP '2019-10-01 00:00:01.000001')|
+----------------------------------------------------------+
|                                                  1.000001|
+----------------------------------------------------------+
SELECT date_part('days', interval 5 days 3 hours 7 minutes);
+-------------------------------------------------+
|date_part(days, INTERVAL '5 03:07' DAY TO MINUTE)|
+-------------------------------------------------+
|                                                5|
+-------------------------------------------------+
SELECT date_part('seconds', interval 5 hours 30 seconds 1 milliseconds 1 microseconds);
+-------------------------------------------------------------+
|date_part(seconds, INTERVAL '05:00:30.001001' HOUR TO SECOND)|
+-------------------------------------------------------------+
|                                                    30.001001|
+-------------------------------------------------------------+
SELECT date_part('MONTH', INTERVAL '2021-11' YEAR TO MONTH);
+--------------------------------------------------+
|date_part(MONTH, INTERVAL '2021-11' YEAR TO MONTH)|
+--------------------------------------------------+
|                                                11|
+--------------------------------------------------+
SELECT date_part('MINUTE', INTERVAL '123 23:55:59.002001' DAY TO SECOND);
+---------------------------------------------------------------+
|date_part(MINUTE, INTERVAL '123 23:55:59.002001' DAY TO SECOND)|
+---------------------------------------------------------------+
|                                                             55|
+---------------------------------------------------------------+
-- date_sub
SELECT date_sub('2016-07-30', 1);
+-----------------------+
|date_sub(2016-07-30, 1)|
+-----------------------+
|             2016-07-29|
+-----------------------+
-- date_trunc
SELECT date_trunc('YEAR', '2015-03-05T09:32:05.359');
+-----------------------------------------+
|date_trunc(YEAR, 2015-03-05T09:32:05.359)|
+-----------------------------------------+
|                      2015-01-01 00:00:00|
+-----------------------------------------+
SELECT date_trunc('MM', '2015-03-05T09:32:05.359');
+---------------------------------------+
|date_trunc(MM, 2015-03-05T09:32:05.359)|
+---------------------------------------+
|                    2015-03-01 00:00:00|
+---------------------------------------+
SELECT date_trunc('DD', '2015-03-05T09:32:05.359');
+---------------------------------------+
|date_trunc(DD, 2015-03-05T09:32:05.359)|
+---------------------------------------+
|                    2015-03-05 00:00:00|
+---------------------------------------+
SELECT date_trunc('HOUR', '2015-03-05T09:32:05.359');
+-----------------------------------------+
|date_trunc(HOUR, 2015-03-05T09:32:05.359)|
+-----------------------------------------+
|                      2015-03-05 09:00:00|
+-----------------------------------------+
SELECT date_trunc('MILLISECOND', '2015-03-05T09:32:05.123456');
+---------------------------------------------------+
|date_trunc(MILLISECOND, 2015-03-05T09:32:05.123456)|
+---------------------------------------------------+
|                               2015-03-05 09:32:...|
+---------------------------------------------------+
-- dateadd
SELECT dateadd('2016-07-30', 1);
+-----------------------+
|date_add(2016-07-30, 1)|
+-----------------------+
|             2016-07-31|
+-----------------------+
-- datediff
SELECT datediff('2009-07-31', '2009-07-30');
+--------------------------------+
|datediff(2009-07-31, 2009-07-30)|
+--------------------------------+
|                               1|
+--------------------------------+
SELECT datediff('2009-07-30', '2009-07-31');
+--------------------------------+
|datediff(2009-07-30, 2009-07-31)|
+--------------------------------+
|                              -1|
+--------------------------------+
-- datepart
SELECT datepart('YEAR', TIMESTAMP '2019-08-12 01:00:00.123456');
+----------------------------------------------------------+
|datepart(YEAR FROM TIMESTAMP '2019-08-12 01:00:00.123456')|
+----------------------------------------------------------+
|                                                      2019|
+----------------------------------------------------------+
SELECT datepart('week', timestamp'2019-08-12 01:00:00.123456');
+----------------------------------------------------------+
|datepart(week FROM TIMESTAMP '2019-08-12 01:00:00.123456')|
+----------------------------------------------------------+
|                                                        33|
+----------------------------------------------------------+
SELECT datepart('doy', DATE'2019-08-12');
+------------------------------------+
|datepart(doy FROM DATE '2019-08-12')|
+------------------------------------+
|                                 224|
+------------------------------------+
SELECT datepart('SECONDS', timestamp'2019-10-01 00:00:01.000001');
+-------------------------------------------------------------+
|datepart(SECONDS FROM TIMESTAMP '2019-10-01 00:00:01.000001')|
+-------------------------------------------------------------+
|                                                     1.000001|
+-------------------------------------------------------------+
SELECT datepart('days', interval 5 days 3 hours 7 minutes);
+----------------------------------------------------+
|datepart(days FROM INTERVAL '5 03:07' DAY TO MINUTE)|
+----------------------------------------------------+
|                                                   5|
+----------------------------------------------------+
SELECT datepart('seconds', interval 5 hours 30 seconds 1 milliseconds 1 microseconds);
+----------------------------------------------------------------+
|datepart(seconds FROM INTERVAL '05:00:30.001001' HOUR TO SECOND)|
+----------------------------------------------------------------+
|                                                       30.001001|
+----------------------------------------------------------------+
SELECT datepart('MONTH', INTERVAL '2021-11' YEAR TO MONTH);
+-----------------------------------------------------+
|datepart(MONTH FROM INTERVAL '2021-11' YEAR TO MONTH)|
+-----------------------------------------------------+
|                                                   11|
+-----------------------------------------------------+
SELECT datepart('MINUTE', INTERVAL '123 23:55:59.002001' DAY TO SECOND);
+------------------------------------------------------------------+
|datepart(MINUTE FROM INTERVAL '123 23:55:59.002001' DAY TO SECOND)|
+------------------------------------------------------------------+
|                                                                55|
+------------------------------------------------------------------+
-- day
SELECT day('2009-07-30');
+---------------+
|day(2009-07-30)|
+---------------+
|             30|
+---------------+
-- dayofmonth
SELECT dayofmonth('2009-07-30');
+----------------------+
|dayofmonth(2009-07-30)|
+----------------------+
|                    30|
+----------------------+
-- dayofweek
SELECT dayofweek('2009-07-30');
+---------------------+
|dayofweek(2009-07-30)|
+---------------------+
|                    5|
+---------------------+
-- dayofyear
SELECT dayofyear('2016-04-09');
+---------------------+
|dayofyear(2016-04-09)|
+---------------------+
|                  100|
+---------------------+
-- extract
SELECT extract(YEAR FROM TIMESTAMP '2019-08-12 01:00:00.123456');
+---------------------------------------------------------+
|extract(YEAR FROM TIMESTAMP '2019-08-12 01:00:00.123456')|
+---------------------------------------------------------+
|                                                     2019|
+---------------------------------------------------------+
SELECT extract(week FROM timestamp'2019-08-12 01:00:00.123456');
+---------------------------------------------------------+
|extract(week FROM TIMESTAMP '2019-08-12 01:00:00.123456')|
+---------------------------------------------------------+
|                                                       33|
+---------------------------------------------------------+
SELECT extract(doy FROM DATE'2019-08-12');
+-----------------------------------+
|extract(doy FROM DATE '2019-08-12')|
+-----------------------------------+
|                                224|
+-----------------------------------+
SELECT extract(SECONDS FROM timestamp'2019-10-01 00:00:01.000001');
+------------------------------------------------------------+
|extract(SECONDS FROM TIMESTAMP '2019-10-01 00:00:01.000001')|
+------------------------------------------------------------+
|                                                    1.000001|
+------------------------------------------------------------+
SELECT extract(days FROM interval 5 days 3 hours 7 minutes);
+---------------------------------------------------+
|extract(days FROM INTERVAL '5 03:07' DAY TO MINUTE)|
+---------------------------------------------------+
|                                                  5|
+---------------------------------------------------+
SELECT extract(seconds FROM interval 5 hours 30 seconds 1 milliseconds 1 microseconds);
+---------------------------------------------------------------+
|extract(seconds FROM INTERVAL '05:00:30.001001' HOUR TO SECOND)|
+---------------------------------------------------------------+
|                                                      30.001001|
+---------------------------------------------------------------+
SELECT extract(MONTH FROM INTERVAL '2021-11' YEAR TO MONTH);
+----------------------------------------------------+
|extract(MONTH FROM INTERVAL '2021-11' YEAR TO MONTH)|
+----------------------------------------------------+
|                                                  11|
+----------------------------------------------------+
SELECT extract(MINUTE FROM INTERVAL '123 23:55:59.002001' DAY TO SECOND);
+-----------------------------------------------------------------+
|extract(MINUTE FROM INTERVAL '123 23:55:59.002001' DAY TO SECOND)|
+-----------------------------------------------------------------+
|                                                               55|
+-----------------------------------------------------------------+
-- from_unixtime
SELECT from_unixtime(0, 'yyyy-MM-dd HH:mm:ss');
+-------------------------------------+
|from_unixtime(0, yyyy-MM-dd HH:mm:ss)|
+-------------------------------------+
|                  1970-01-01 09:00:00|
+-------------------------------------+
SELECT from_unixtime(0);
+-------------------------------------+
|from_unixtime(0, yyyy-MM-dd HH:mm:ss)|
+-------------------------------------+
|                  1970-01-01 09:00:00|
+-------------------------------------+
-- from_utc_timestamp
SELECT from_utc_timestamp('2016-08-31', 'Asia/Seoul');
+------------------------------------------+
|from_utc_timestamp(2016-08-31, Asia/Seoul)|
+------------------------------------------+
|                       2016-08-31 09:00:00|
+------------------------------------------+
-- hour
SELECT hour('2009-07-30 12:58:59');
+-------------------------+
|hour(2009-07-30 12:58:59)|
+-------------------------+
|                       12|
+-------------------------+
-- last_day
SELECT last_day('2009-01-12');
+--------------------+
|last_day(2009-01-12)|
+--------------------+
|          2009-01-31|
+--------------------+
-- localtimestamp
SELECT localtimestamp();
+--------------------+
|    localtimestamp()|
+--------------------+
|2024-02-24 16:36:...|
+--------------------+
-- make_date
SELECT make_date(2013, 7, 15);
+----------------------+
|make_date(2013, 7, 15)|
+----------------------+
|            2013-07-15|
+----------------------+
SELECT make_date(2019, 7, NULL);
+------------------------+
|make_date(2019, 7, NULL)|
+------------------------+
|                    NULL|
+------------------------+
-- make_dt_interval
SELECT make_dt_interval(1, 12, 30, 01.001001);
+-------------------------------------+
|make_dt_interval(1, 12, 30, 1.001001)|
+-------------------------------------+
|                 INTERVAL '1 12:30...|
+-------------------------------------+
SELECT make_dt_interval(2);
+-----------------------------------+
|make_dt_interval(2, 0, 0, 0.000000)|
+-----------------------------------+
|               INTERVAL '2 00:00...|
+-----------------------------------+
SELECT make_dt_interval(100, null, 3);
+----------------------------------------+
|make_dt_interval(100, NULL, 3, 0.000000)|
+----------------------------------------+
|                                    NULL|
+----------------------------------------+
-- make_interval
SELECT make_interval(100, 11, 1, 1, 12, 30, 01.001001);
+----------------------------------------------+
|make_interval(100, 11, 1, 1, 12, 30, 1.001001)|
+----------------------------------------------+
|                          100 years 11 mont...|
+----------------------------------------------+
SELECT make_interval(100, null, 3);
+----------------------------------------------+
|make_interval(100, NULL, 3, 0, 0, 0, 0.000000)|
+----------------------------------------------+
|                                          NULL|
+----------------------------------------------+
SELECT make_interval(0, 1, 0, 1, 0, 0, 100.000001);
+-------------------------------------------+
|make_interval(0, 1, 0, 1, 0, 0, 100.000001)|
+-------------------------------------------+
|                       1 months 1 days 1...|
+-------------------------------------------+
-- make_timestamp
SELECT make_timestamp(2014, 12, 28, 6, 30, 45.887);
+-------------------------------------------+
|make_timestamp(2014, 12, 28, 6, 30, 45.887)|
+-------------------------------------------+
|                       2014-12-28 06:30:...|
+-------------------------------------------+
SELECT make_timestamp(2014, 12, 28, 6, 30, 45.887, 'CET');
+------------------------------------------------+
|make_timestamp(2014, 12, 28, 6, 30, 45.887, CET)|
+------------------------------------------------+
|                            2014-12-28 14:30:...|
+------------------------------------------------+
SELECT make_timestamp(2019, 6, 30, 23, 59, 60);
+---------------------------------------+
|make_timestamp(2019, 6, 30, 23, 59, 60)|
+---------------------------------------+
|                    2019-07-01 00:00:00|
+---------------------------------------+
SELECT make_timestamp(2019, 6, 30, 23, 59, 1);
+--------------------------------------+
|make_timestamp(2019, 6, 30, 23, 59, 1)|
+--------------------------------------+
|                   2019-06-30 23:59:01|
+--------------------------------------+
SELECT make_timestamp(null, 7, 22, 15, 30, 0);
+--------------------------------------+
|make_timestamp(NULL, 7, 22, 15, 30, 0)|
+--------------------------------------+
|                                  NULL|
+--------------------------------------+
-- make_timestamp_ltz
SELECT make_timestamp_ltz(2014, 12, 28, 6, 30, 45.887);
+-----------------------------------------------+
|make_timestamp_ltz(2014, 12, 28, 6, 30, 45.887)|
+-----------------------------------------------+
|                           2014-12-28 06:30:...|
+-----------------------------------------------+
SELECT make_timestamp_ltz(2014, 12, 28, 6, 30, 45.887, 'CET');
+----------------------------------------------------+
|make_timestamp_ltz(2014, 12, 28, 6, 30, 45.887, CET)|
+----------------------------------------------------+
|                                2014-12-28 14:30:...|
+----------------------------------------------------+
SELECT make_timestamp_ltz(2019, 6, 30, 23, 59, 60);
+-------------------------------------------+
|make_timestamp_ltz(2019, 6, 30, 23, 59, 60)|
+-------------------------------------------+
|                        2019-07-01 00:00:00|
+-------------------------------------------+
SELECT make_timestamp_ltz(null, 7, 22, 15, 30, 0);
+------------------------------------------+
|make_timestamp_ltz(NULL, 7, 22, 15, 30, 0)|
+------------------------------------------+
|                                      NULL|
+------------------------------------------+
-- make_timestamp_ntz
SELECT make_timestamp_ntz(2014, 12, 28, 6, 30, 45.887);
+-----------------------------------------------+
|make_timestamp_ntz(2014, 12, 28, 6, 30, 45.887)|
+-----------------------------------------------+
|                           2014-12-28 06:30:...|
+-----------------------------------------------+
SELECT make_timestamp_ntz(2019, 6, 30, 23, 59, 60);
+-------------------------------------------+
|make_timestamp_ntz(2019, 6, 30, 23, 59, 60)|
+-------------------------------------------+
|                        2019-07-01 00:00:00|
+-------------------------------------------+
SELECT make_timestamp_ntz(null, 7, 22, 15, 30, 0);
+------------------------------------------+
|make_timestamp_ntz(NULL, 7, 22, 15, 30, 0)|
+------------------------------------------+
|                                      NULL|
+------------------------------------------+
-- make_ym_interval
SELECT make_ym_interval(1, 2);
+----------------------+
|make_ym_interval(1, 2)|
+----------------------+
|  INTERVAL '1-2' YE...|
+----------------------+
SELECT make_ym_interval(1, 0);
+----------------------+
|make_ym_interval(1, 0)|
+----------------------+
|  INTERVAL '1-0' YE...|
+----------------------+
SELECT make_ym_interval(-1, 1);
+-----------------------+
|make_ym_interval(-1, 1)|
+-----------------------+
|   INTERVAL '-0-11' ...|
+-----------------------+
SELECT make_ym_interval(2);
+----------------------+
|make_ym_interval(2, 0)|
+----------------------+
|  INTERVAL '2-0' YE...|
+----------------------+
-- minute
SELECT minute('2009-07-30 12:58:59');
+---------------------------+
|minute(2009-07-30 12:58:59)|
+---------------------------+
|                         58|
+---------------------------+
-- month
SELECT month('2016-07-30');
+-----------------+
|month(2016-07-30)|
+-----------------+
|                7|
+-----------------+
-- months_between
SELECT months_between('1997-02-28 10:30:00', '1996-10-30');
+-----------------------------------------------------+
|months_between(1997-02-28 10:30:00, 1996-10-30, true)|
+-----------------------------------------------------+
|                                           3.94959677|
+-----------------------------------------------------+
SELECT months_between('1997-02-28 10:30:00', '1996-10-30', false);
+------------------------------------------------------+
|months_between(1997-02-28 10:30:00, 1996-10-30, false)|
+------------------------------------------------------+
|                                    3.9495967741935485|
+------------------------------------------------------+
-- next_day
SELECT next_day('2015-01-14', 'TU');
+------------------------+
|next_day(2015-01-14, TU)|
+------------------------+
|              2015-01-20|
+------------------------+
-- now
SELECT now();
+--------------------+
|               now()|
+--------------------+
|2024-02-24 16:36:...|
+--------------------+
-- quarter
SELECT quarter('2016-08-31');
+-------------------+
|quarter(2016-08-31)|
+-------------------+
|                  3|
+-------------------+
-- second
SELECT second('2009-07-30 12:58:59');
+---------------------------+
|second(2009-07-30 12:58:59)|
+---------------------------+
|                         59|
+---------------------------+
-- session_window
SELECT a, session_window.start, session_window.end, count(*) as cnt FROM VALUES ('A1', '2021-01-01 00:00:00'), ('A1', '2021-01-01 00:04:30'), ('A1', '2021-01-01 00:10:00'), ('A2', '2021-01-01 00:01:00') AS tab(a, b) GROUP by a, session_window(b, '5 minutes') ORDER BY a, start;
+---+-------------------+-------------------+---+
|  a|              start|                end|cnt|
+---+-------------------+-------------------+---+
| A1|2021-01-01 00:00:00|2021-01-01 00:09:30|  2|
| A1|2021-01-01 00:10:00|2021-01-01 00:15:00|  1|
| A2|2021-01-01 00:01:00|2021-01-01 00:06:00|  1|
+---+-------------------+-------------------+---+
SELECT a, session_window.start, session_window.end, count(*) as cnt FROM VALUES ('A1', '2021-01-01 00:00:00'), ('A1', '2021-01-01 00:04:30'), ('A1', '2021-01-01 00:10:00'), ('A2', '2021-01-01 00:01:00'), ('A2', '2021-01-01 00:04:30') AS tab(a, b) GROUP by a, session_window(b, CASE WHEN a = 'A1' THEN '5 minutes' WHEN a = 'A2' THEN '1 minute' ELSE '10 minutes' END) ORDER BY a, start;
+---+-------------------+-------------------+---+
|  a|              start|                end|cnt|
+---+-------------------+-------------------+---+
| A1|2021-01-01 00:00:00|2021-01-01 00:09:30|  2|
| A1|2021-01-01 00:10:00|2021-01-01 00:15:00|  1|
| A2|2021-01-01 00:01:00|2021-01-01 00:02:00|  1|
| A2|2021-01-01 00:04:30|2021-01-01 00:05:30|  1|
+---+-------------------+-------------------+---+
-- timestamp_micros
SELECT timestamp_micros(1230219000123123);
+----------------------------------+
|timestamp_micros(1230219000123123)|
+----------------------------------+
|              2008-12-26 00:30:...|
+----------------------------------+
-- timestamp_millis
SELECT timestamp_millis(1230219000123);
+-------------------------------+
|timestamp_millis(1230219000123)|
+-------------------------------+
|           2008-12-26 00:30:...|
+-------------------------------+
-- timestamp_seconds
SELECT timestamp_seconds(1230219000);
+-----------------------------+
|timestamp_seconds(1230219000)|
+-----------------------------+
|          2008-12-26 00:30:00|
+-----------------------------+
SELECT timestamp_seconds(1230219000.123);
+---------------------------------+
|timestamp_seconds(1230219000.123)|
+---------------------------------+
|             2008-12-26 00:30:...|
+---------------------------------+
-- to_date
SELECT to_date('2009-07-30 04:17:52');
+----------------------------+
|to_date(2009-07-30 04:17:52)|
+----------------------------+
|                  2009-07-30|
+----------------------------+
SELECT to_date('2016-12-31', 'yyyy-MM-dd');
+-------------------------------+
|to_date(2016-12-31, yyyy-MM-dd)|
+-------------------------------+
|                     2016-12-31|
+-------------------------------+
-- to_timestamp
SELECT to_timestamp('2016-12-31 00:12:00');
+---------------------------------+
|to_timestamp(2016-12-31 00:12:00)|
+---------------------------------+
|              2016-12-31 00:12:00|
+---------------------------------+
SELECT to_timestamp('2016-12-31', 'yyyy-MM-dd');
+------------------------------------+
|to_timestamp(2016-12-31, yyyy-MM-dd)|
+------------------------------------+
|                 2016-12-31 00:00:00|
+------------------------------------+
-- to_timestamp_ltz
SELECT to_timestamp_ltz('2016-12-31 00:12:00');
+-------------------------------------+
|to_timestamp_ltz(2016-12-31 00:12:00)|
+-------------------------------------+
|                  2016-12-31 00:12:00|
+-------------------------------------+
SELECT to_timestamp_ltz('2016-12-31', 'yyyy-MM-dd');
+----------------------------------------+
|to_timestamp_ltz(2016-12-31, yyyy-MM-dd)|
+----------------------------------------+
|                     2016-12-31 00:00:00|
+----------------------------------------+
-- to_timestamp_ntz
SELECT to_timestamp_ntz('2016-12-31 00:12:00');
+-------------------------------------+
|to_timestamp_ntz(2016-12-31 00:12:00)|
+-------------------------------------+
|                  2016-12-31 00:12:00|
+-------------------------------------+
SELECT to_timestamp_ntz('2016-12-31', 'yyyy-MM-dd');
+----------------------------------------+
|to_timestamp_ntz(2016-12-31, yyyy-MM-dd)|
+----------------------------------------+
|                     2016-12-31 00:00:00|
+----------------------------------------+
-- to_unix_timestamp
SELECT to_unix_timestamp('2016-04-08', 'yyyy-MM-dd');
+-----------------------------------------+
|to_unix_timestamp(2016-04-08, yyyy-MM-dd)|
+-----------------------------------------+
|                               1460041200|
+-----------------------------------------+
-- to_utc_timestamp
SELECT to_utc_timestamp('2016-08-31', 'Asia/Seoul');
+----------------------------------------+
|to_utc_timestamp(2016-08-31, Asia/Seoul)|
+----------------------------------------+
|                     2016-08-30 15:00:00|
+----------------------------------------+
-- trunc
SELECT trunc('2019-08-04', 'week');
+-----------------------+
|trunc(2019-08-04, week)|
+-----------------------+
|             2019-07-29|
+-----------------------+
SELECT trunc('2019-08-04', 'quarter');
+--------------------------+
|trunc(2019-08-04, quarter)|
+--------------------------+
|                2019-07-01|
+--------------------------+
SELECT trunc('2009-02-12', 'MM');
+---------------------+
|trunc(2009-02-12, MM)|
+---------------------+
|           2009-02-01|
+---------------------+
SELECT trunc('2015-10-27', 'YEAR');
+-----------------------+
|trunc(2015-10-27, YEAR)|
+-----------------------+
|             2015-01-01|
+-----------------------+
-- try_to_timestamp
SELECT try_to_timestamp('2016-12-31 00:12:00');
+-------------------------------------+
|try_to_timestamp(2016-12-31 00:12:00)|
+-------------------------------------+
|                  2016-12-31 00:12:00|
+-------------------------------------+
SELECT try_to_timestamp('2016-12-31', 'yyyy-MM-dd');
+----------------------------------------+
|try_to_timestamp(2016-12-31, yyyy-MM-dd)|
+----------------------------------------+
|                     2016-12-31 00:00:00|
+----------------------------------------+
SELECT try_to_timestamp('foo', 'yyyy-MM-dd');
+---------------------------------+
|try_to_timestamp(foo, yyyy-MM-dd)|
+---------------------------------+
|                             NULL|
+---------------------------------+
-- unix_date
SELECT unix_date(DATE("1970-01-02"));
+---------------------+
|unix_date(1970-01-02)|
+---------------------+
|                    1|
+---------------------+
-- unix_micros
SELECT unix_micros(TIMESTAMP('1970-01-01 00:00:01Z'));
+---------------------------------+
|unix_micros(1970-01-01 00:00:01Z)|
+---------------------------------+
|                          1000000|
+---------------------------------+
-- unix_millis
SELECT unix_millis(TIMESTAMP('1970-01-01 00:00:01Z'));
+---------------------------------+
|unix_millis(1970-01-01 00:00:01Z)|
+---------------------------------+
|                             1000|
+---------------------------------+
-- unix_seconds
SELECT unix_seconds(TIMESTAMP('1970-01-01 00:00:01Z'));
+----------------------------------+
|unix_seconds(1970-01-01 00:00:01Z)|
+----------------------------------+
|                                 1|
+----------------------------------+
-- unix_timestamp
SELECT unix_timestamp();
+--------------------------------------------------------+
|unix_timestamp(current_timestamp(), yyyy-MM-dd HH:mm:ss)|
+--------------------------------------------------------+
|                                              1708760216|
+--------------------------------------------------------+
SELECT unix_timestamp('2016-04-08', 'yyyy-MM-dd');
+--------------------------------------+
|unix_timestamp(2016-04-08, yyyy-MM-dd)|
+--------------------------------------+
|                            1460041200|
+--------------------------------------+
-- weekday
SELECT weekday('2009-07-30');
+-------------------+
|weekday(2009-07-30)|
+-------------------+
|                  3|
+-------------------+
-- weekofyear
SELECT weekofyear('2008-02-20');
+----------------------+
|weekofyear(2008-02-20)|
+----------------------+
|                     8|
+----------------------+
-- window
SELECT a, window.start, window.end, count(*) as cnt FROM VALUES ('A1', '2021-01-01 00:00:00'), ('A1', '2021-01-01 00:04:30'), ('A1', '2021-01-01 00:06:00'), ('A2', '2021-01-01 00:01:00') AS tab(a, b) GROUP by a, window(b, '5 minutes') ORDER BY a, start;
+---+-------------------+-------------------+---+
|  a|              start|                end|cnt|
+---+-------------------+-------------------+---+
| A1|2021-01-01 00:00:00|2021-01-01 00:05:00|  2|
| A1|2021-01-01 00:05:00|2021-01-01 00:10:00|  1|
| A2|2021-01-01 00:00:00|2021-01-01 00:05:00|  1|
+---+-------------------+-------------------+---+
SELECT a, window.start, window.end, count(*) as cnt FROM VALUES ('A1', '2021-01-01 00:00:00'), ('A1', '2021-01-01 00:04:30'), ('A1', '2021-01-01 00:06:00'), ('A2', '2021-01-01 00:01:00') AS tab(a, b) GROUP by a, window(b, '10 minutes', '5 minutes') ORDER BY a, start;
+---+-------------------+-------------------+---+
|  a|              start|                end|cnt|
+---+-------------------+-------------------+---+
| A1|2020-12-31 23:55:00|2021-01-01 00:05:00|  2|
| A1|2021-01-01 00:00:00|2021-01-01 00:10:00|  3|
| A1|2021-01-01 00:05:00|2021-01-01 00:15:00|  1|
| A2|2020-12-31 23:55:00|2021-01-01 00:05:00|  1|
| A2|2021-01-01 00:00:00|2021-01-01 00:10:00|  1|
+---+-------------------+-------------------+---+
-- window_time
SELECT a, window.start as start, window.end as end, window_time(window), cnt FROM (SELECT a, window, count(*) as cnt FROM VALUES ('A1', '2021-01-01 00:00:00'), ('A1', '2021-01-01 00:04:30'), ('A1', '2021-01-01 00:06:00'), ('A2', '2021-01-01 00:01:00') AS tab(a, b) GROUP by a, window(b, '5 minutes') ORDER BY a, window.start);
+---+-------------------+-------------------+--------------------+---+
|  a|              start|                end| window_time(window)|cnt|
+---+-------------------+-------------------+--------------------+---+
| A1|2021-01-01 00:00:00|2021-01-01 00:05:00|2021-01-01 00:04:...|  2|
| A1|2021-01-01 00:05:00|2021-01-01 00:10:00|2021-01-01 00:09:...|  1|
| A2|2021-01-01 00:00:00|2021-01-01 00:05:00|2021-01-01 00:04:...|  1|
+---+-------------------+-------------------+--------------------+---+
-- year
SELECT year('2016-07-30');
+----------------+
|year(2016-07-30)|
+----------------+
|            2016|
+----------------+
```

#### 집계 함수
<a name="supported-sql-aggregate"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

집계 함수는 행의 값에 대해 작동하여 합계, 평균, 계산, 최소값/최대값, 표준 편차, 추정과 같은 수학 계산과 일부 비수학 연산을 수행합니다.

**구문 **

```
aggregate_function(input1 [, input2, ...]) FILTER (WHERE boolean_expression) 
```

**파라미터**
+ `boolean_expression` - 결과 유형 부울로 평가되는 표현식을 지정합니다. 논리 연산자(AND, OR)를 사용하여 둘 이상의 표현식을 결합할 수 있습니다.

**순서 지정 집계 함수 **

이 집계 함수는 다른 집계 함수와 다른 구문을 사용하여 값을 정렬할 표현식(일반적으로 열 이름)을 지정합니다.

**구문 **

```
{ PERCENTILE_CONT | PERCENTILE_DISC }(percentile) WITHIN GROUP (ORDER BY { order_by_expression [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [ , ... ] }) FILTER (WHERE boolean_expression) 
```

**파라미터**
+ `percentile` - 찾으려는 값의 백분위수입니다. 백분위수는 0.0에서 1.0 사이의 상수여야 합니다.
+ `order_by_expression` - 값을 집계하기 전에 정렬할 표현식(일반적으로 열 이름)입니다.
+ `boolean_expression` - 결과 유형 부울로 평가되는 표현식을 지정합니다. 논리 연산자(AND, OR)를 사용하여 둘 이상의 표현식을 결합할 수 있습니다.

**예시**

```
CREATE OR REPLACE TEMPORARY VIEW basic_pays AS SELECT * FROM VALUES
('Jane Doe','Accounting',8435),
('Akua Mansa','Accounting',9998),
('John Doe','Accounting',8992),
('Juan Li','Accounting',8870),
('Carlos Salazar','Accounting',11472),
('Arnav Desai','Accounting',6627),
('Saanvi Sarkar','IT',8113),
('Shirley Rodriguez','IT',5186),
('Nikki Wolf','Sales',9181),
('Alejandro Rosalez','Sales',9441),
('Nikhil Jayashankar','Sales',6660),
('Richard Roe','Sales',10563),
('Pat Candella','SCM',10449),
('Gerard Hernandez','SCM',6949),
('Pamela Castillo','SCM',11303),
('Paulo Santos','SCM',11798),
('Jorge Souza','SCM',10586)
AS basic_pays(employee_name, department, salary);
SELECT * FROM basic_pays;
+-------------------+----------+------+
|    employee_name  |department|salary|
+-------------------+----------+------+
| Arnav Desai       |Accounting|  6627|
| Jorge Souza       |       SCM| 10586|
| Jane Doe          |Accounting|  8435|
| Nikhil Jayashankar|     Sales|  6660|
| Diego Vanauf      |     Sales| 10563|
| Carlos Salazar    |Accounting| 11472|
| Gerard Hernandez  |       SCM|  6949|
| John Doe          |Accounting|  8992|
| Nikki Wolf        |     Sales|  9181|
| Paulo Santos      |       SCM| 11798|
| Saanvi Sarkar     |        IT|  8113|
| Shirley Rodriguez |        IT|  5186|
| Pat Candella      |       SCM| 10449|
| Akua Mansa        |Accounting|  9998|
| Pamela Castillo   |       SCM| 11303|
| Alejandro Rosalez |     Sales|  9441|
| Juan Li           |Accounting|  8870|
+-------------------+----------+------+
SELECT
department,
percentile_cont(0.25) WITHIN GROUP (ORDER BY salary) AS pc1,
percentile_cont(0.25) WITHIN GROUP (ORDER BY salary) FILTER (WHERE employee_name LIKE '%Bo%') AS pc2,
percentile_cont(0.25) WITHIN GROUP (ORDER BY salary DESC) AS pc3,
percentile_cont(0.25) WITHIN GROUP (ORDER BY salary DESC) FILTER (WHERE employee_name LIKE '%Bo%') AS pc4,
percentile_disc(0.25) WITHIN GROUP (ORDER BY salary) AS pd1,
percentile_disc(0.25) WITHIN GROUP (ORDER BY salary) FILTER (WHERE employee_name LIKE '%Bo%') AS pd2,
percentile_disc(0.25) WITHIN GROUP (ORDER BY salary DESC) AS pd3,
percentile_disc(0.25) WITHIN GROUP (ORDER BY salary DESC) FILTER (WHERE employee_name LIKE '%Bo%') AS pd4
FROM basic_pays
GROUP BY department
ORDER BY department;
+----------+-------+--------+-------+--------+-----+-----+-----+-----+
|department|    pc1|     pc2|    pc3|     pc4|  pd1|  pd2|  pd3|  pd4|
+----------+-------+--------+-------+--------+-----+-----+-----+-----+
|Accounting|8543.75| 7838.25| 9746.5|10260.75| 8435| 6627| 9998|11472|
|        IT|5917.75|    NULL|7381.25|    NULL| 5186| NULL| 8113| NULL|
|     Sales|8550.75|    NULL| 9721.5|    NULL| 6660| NULL|10563| NULL|
|       SCM|10449.0|10786.25|11303.0|11460.75|10449|10449|11303|11798|
+----------+-------+--------+-------+--------+-----+-----+-----+-----+
```

#### 조건 함수
<a name="supported-sql-conditional"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).


****  

| 함수 | 설명 | 
| --- | --- | 
| coalesce(expr1, expr2, ...) | 존재하는 경우, 첫 번째 null이 아닌 인수를 반환합니다. 그렇지 않은 경우 null입니다. | 
| if(expr1, expr2, expr3) | expr1이 true로 평가되면 expr2를 반환하고, 그렇지 않으면 expr3을 반환합니다. | 
| ifnull(expr1, expr2) | expr1이 null이면 expr1을 반환하고, 그렇지 않으면 expr2를 반환합니다. | 
| nanvl(expr1, expr2) | NaN이 아니면 expr1을 반환하고, 그렇지 않으면 expr2를 반환합니다. | 
| nullif(expr1, expr2) | expr1가 expr2와 같으면 null을 반환하고, 그렇지 않으면 expr1을 반환합니다. | 
| nvl(expr1, expr2) | expr1이 null이면 expr1을 반환하고, 그렇지 않으면 expr2를 반환합니다. | 
| nvl2(expr1, expr2, expr3) | expr1이 null이 아니면 expr3을 반환하고, 그렇지 않으면 expr2를 반환합니다. | 
| CASE WHEN expr1 THEN expr2 [WHEN expr3 THEN expr4]\$1 [ELSE expr5] END | expr1 = true이면 expr2를 반환하고, expr3 = true이면 expr4를 반환하고, 그렇지 않으면 expr5를 반환합니다. | 

**예시**

```
-- coalesce
SELECT coalesce(NULL, 1, NULL);
+-----------------------+
|coalesce(NULL, 1, NULL)|
+-----------------------+
|                      1|
+-----------------------+
-- if
SELECT if(1 < 2, 'a', 'b');
+-------------------+
|(IF((1 < 2), a, b))|
+-------------------+
|                  a|
+-------------------+
-- ifnull
SELECT ifnull(NULL, array('2'));
+----------------------+
|ifnull(NULL, array(2))|
+----------------------+
|                   [2]|
+----------------------+
-- nanvl
SELECT nanvl(cast('NaN' as double), 123);
+-------------------------------+
|nanvl(CAST(NaN AS DOUBLE), 123)|
+-------------------------------+
|                          123.0|
+-------------------------------+
-- nullif
SELECT nullif(2, 2);
+------------+
|nullif(2, 2)|
+------------+
|        NULL|
+------------+
-- nvl
SELECT nvl(NULL, array('2'));
+-------------------+
|nvl(NULL, array(2))|
+-------------------+
|                [2]|
+-------------------+
-- nvl2
SELECT nvl2(NULL, 2, 1);
+----------------+
|nvl2(NULL, 2, 1)|
+----------------+
|               1|
+----------------+
-- when
SELECT CASE WHEN 1 > 0 THEN 1 WHEN 2 > 0 THEN 2.0 ELSE 1.2 END;
+-----------------------------------------------------------+
|CASE WHEN (1 > 0) THEN 1 WHEN (2 > 0) THEN 2.0 ELSE 1.2 END|
+-----------------------------------------------------------+
|                                                        1.0|
+-----------------------------------------------------------+
SELECT CASE WHEN 1 < 0 THEN 1 WHEN 2 > 0 THEN 2.0 ELSE 1.2 END;
+-----------------------------------------------------------+
|CASE WHEN (1 < 0) THEN 1 WHEN (2 > 0) THEN 2.0 ELSE 1.2 END|
+-----------------------------------------------------------+
|                                                        2.0|
+-----------------------------------------------------------+
SELECT CASE WHEN 1 < 0 THEN 1 WHEN 2 < 0 THEN 2.0 END;
+--------------------------------------------------+
|CASE WHEN (1 < 0) THEN 1 WHEN (2 < 0) THEN 2.0 END|
+--------------------------------------------------+
|                                              NULL|
+--------------------------------------------------+
```

#### JSON 함수
<a name="supported-sql-json"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).




****  

| 함수 | 설명 | 
| --- | --- | 
| from\$1json(jsonStr, schema[, options]) | 지정된 `jsonStr` 및 `schema`의 구문 값을 반환합니다. | 
| get\$1json\$1object(json\$1txt, path) | `path`에서 json 객체를 추출합니다. | 
| json\$1array\$1length(jsonArray) | JSON 문자열의 바깥쪽 배열에 속한 요소 수를 반환합니다. | 
| json\$1object\$1keys(json\$1object) | 가장 바깥쪽 JSON 객체의 모든 키를 배열로 반환합니다. | 
| json\$1tuple(jsonStr, p1, p2, ..., pn) | 함수 get\$1json\$1object와 같은 튜플을 반환하지만 여러 이름을 사용합니다. 모든 입력 파라미터와 출력 열 유형은 문자열입니다. | 
| schema\$1of\$1json(json[, options]) | JSON 문자열의 DDL 형식으로 스키마를 반환합니다. | 
| to\$1json(expr[, options]) | 지정된 구문 값을 가진 JSON 문자열을 반환합니다. | 

**예시**

```
-- from_json
SELECT from_json('{"a":1, "b":0.8}', 'a INT, b DOUBLE');
+---------------------------+
| from_json({"a":1, "b":0.8}) |
+---------------------------+
| {1, 0.8}                  |
+---------------------------+

SELECT from_json('{"time":"26/08/2015"}', 'time Timestamp', map('timestampFormat', 'dd/MM/yyyy'));
+--------------------------------+
| from_json({"time":"26/08/2015"}) |
+--------------------------------+
| {2015-08-26 00:00...           |
+--------------------------------+

SELECT from_json('{"teacher": "Alice", "student": [{"name": "Bob", "rank": 1}, {"name": "Charlie", "rank": 2}]}', 'STRUCT<teacher: STRING, student: ARRAY<STRUCT<name: STRING, rank: INT>>>');
+--------------------------------------------------------------------------------------------------------+
| from_json({"teacher": "Alice", "student": [{"name": "Bob", "rank": 1}, {"name": "Charlie", "rank": 2}]}) |
+--------------------------------------------------------------------------------------------------------+
| {Alice, [{Bob, 1}...                                                                                   |
+--------------------------------------------------------------------------------------------------------+

-- get_json_object
SELECT get_json_object('{"a":"b"}', '$.a');
+-------------------------------+
| get_json_object({"a":"b"}, $.a) |
+-------------------------------+
| b                             |
+-------------------------------+

-- json_array_length
SELECT json_array_length('[1,2,3,4]');
+----------------------------+
| json_array_length([1,2,3,4]) |
+----------------------------+
| 4                          |
+----------------------------+

SELECT json_array_length('[1,2,3,{"f1":1,"f2":[5,6]},4]');
+------------------------------------------------+
| json_array_length([1,2,3,{"f1":1,"f2":[5,6]},4]) |
+------------------------------------------------+
| 5                                              |
+------------------------------------------------+

SELECT json_array_length('[1,2');
+-----------------------+
| json_array_length([1,2) |
+-----------------------+
| NULL                  |
+-----------------------+

-- json_object_keys
SELECT json_object_keys('{}');
+--------------------+
| json_object_keys({}) |
+--------------------+
| []                 |
+--------------------+

SELECT json_object_keys('{"key": "value"}');
+----------------------------------+
| json_object_keys({"key": "value"}) |
+----------------------------------+
| [key]                            |
+----------------------------------+

SELECT json_object_keys('{"f1":"abc","f2":{"f3":"a", "f4":"b"}}');
+--------------------------------------------------------+
| json_object_keys({"f1":"abc","f2":{"f3":"a", "f4":"b"}}) |
+--------------------------------------------------------+
| [f1, f2]                                               |
+--------------------------------------------------------+

-- json_tuple
SELECT json_tuple('{"a":1, "b":2}', 'a', 'b');
+---+---+
| c0| c1|
+---+---+
|  1|  2|
+---+---+

-- schema_of_json
SELECT schema_of_json('[{"col":0}]');
+---------------------------+
| schema_of_json([{"col":0}]) |
+---------------------------+
| ARRAY<STRUCT<col:...      |
+---------------------------+

SELECT schema_of_json('[{"col":01}]', map('allowNumericLeadingZeros', 'true'));
+----------------------------+
| schema_of_json([{"col":01}]) |
+----------------------------+
| ARRAY<STRUCT<col:...       |
+----------------------------+

-- to_json
SELECT to_json(named_struct('a', 1, 'b', 2));
+---------------------------------+
| to_json(named_struct(a, 1, b, 2)) |
+---------------------------------+
| {"a":1,"b":2}                   |
+---------------------------------+

SELECT to_json(named_struct('time', to_timestamp('2015-08-26', 'yyyy-MM-dd')), map('timestampFormat', 'dd/MM/yyyy'));
+-----------------------------------------------------------------+
| to_json(named_struct(time, to_timestamp(2015-08-26, yyyy-MM-dd))) |
+-----------------------------------------------------------------+
| {"time":"26/08/20...                                            |
+-----------------------------------------------------------------+

SELECT to_json(array(named_struct('a', 1, 'b', 2)));
+----------------------------------------+
| to_json(array(named_struct(a, 1, b, 2))) |
+----------------------------------------+
| [{"a":1,"b":2}]                        |
+----------------------------------------+

SELECT to_json(map('a', named_struct('b', 1)));
+-----------------------------------+
| to_json(map(a, named_struct(b, 1))) |
+-----------------------------------+
| {"a":{"b":1}}                     |
+-----------------------------------+

SELECT to_json(map(named_struct('a', 1),named_struct('b', 2)));
+----------------------------------------------------+
| to_json(map(named_struct(a, 1), named_struct(b, 2))) |
+----------------------------------------------------+
| {"[1]":{"b":2}}                                    |
+----------------------------------------------------+

SELECT to_json(map('a', 1));
+------------------+
| to_json(map(a, 1)) |
+------------------+
| {"a":1}          |
+------------------+

SELECT to_json(array(map('a', 1)));
+-------------------------+
| to_json(array(map(a, 1))) |
+-------------------------+
| [{"a":1}]               |
+-------------------------+
```

#### 배열 함수
<a name="supported-sql-array"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).


****  

| 함수 | 설명 | 
| --- | --- | 
| array(expr, ...) | 지정된 요소가 있는 배열을 반환합니다. | 
| array\$1append(array, element) | 첫 번째 인수로 전달된 배열 끝에 요소를 추가합니다. 요소 유형은 배열의 요소 유형과 유사해야 합니다. Null 요소도 배열에 추가됩니다. 단, 배열이 전달되면 NULL 출력은 NULL입니다. | 
| array\$1compact(array) | 배열에서 null 값을 제거합니다. | 
| array\$1contains(array, value) | 배열에 값이 포함된 경우 true를 반환합니다. | 
| array\$1distinct(array) | 배열에서 중복 값을 제거합니다. | 
| array\$1except(array1, array2) | 중복 없이 array2에 없는 array1의 요소 배열을 반환합니다. | 
| array\$1insert(x, pos, val) | 배열 x의 인덱스 위치에 val을 배치합니다. 배열 인덱스는 1에서 시작합니다. 함수가 현재 마지막 요소 뒤에 새 요소를 삽입하는 최대 음수 인덱스는 -1입니다. 배열 크기를 초과하는 인덱스가 주어지면 인덱스가 양수일 경우 배열의 뒤에, 음수일 경우 배열의 앞에 null 요소를 채워 넣어 확장합니다. | 
| array\$1intersect(array1, array2) | 중복 없이 array1과 array2의 교차점에 있는 요소의 배열을 반환합니다. | 
| array\$1join(array, delimiter[, nullReplacement]) | null을 대체하기 위해 구분 기호와 선택적 문자열을 사용하여 지정된 배열의 요소를 연결합니다. nullReplacement에 값을 설정하지 않으면 null 값이 필터링됩니다. | 
| array\$1max(array) | 배열의 최대값을 반환합니다. NaN은 이중/부동 소수점 유형에 대한 비NaN 요소보다 큽니다. NULL 요소는 건너뜁니다. | 
| array\$1min(array) | 배열의 최소값을 반환합니다. NaN은 이중/부동 소수점 유형에 대한 비NaN 요소보다 큽니다. NULL 요소는 건너뜁니다. | 
| array\$1position(array, element) | 배열에서 처음으로 일치하는 요소의 (1 기반) 인덱스를 long 형식으로 반환하며, 일치하는 요소가 없으면 0을 반환합니다. | 
| array\$1prepend(array, element) | 첫 번째 인수로 전달된 배열의 시작 부분에 요소를 추가합니다. 요소 유형은 배열의 요소 유형과 동일해야 합니다. Null 요소도 배열 앞에 추가됩니다. 단, 배열이 전달되면 NULL 출력은 NULL입니다. | 
| array\$1remove(array, element) | 배열에서 요소와 동일한 요소를 모두 제거합니다. | 
| array\$1repeat(element, count) | 요소를 count 횟수만큼 포함하는 배열을 반환합니다. | 
| array\$1union(array1, array2) | 중복 없이 array1과 array2의 합집합에 있는 요소의 배열을 반환합니다. | 
| arrays\$1overlap(a1, a2) | a1에 null이 아닌 요소가 하나 이상 포함되어 있고 a2에도 있는 경우 true를 반환합니다. 배열에 공통 요소가 없고 둘 다 비어 있지 않으며 둘 중 하나에 null 요소가 포함된 경우 null이, 그렇지 않은 경우 false가 반환됩니다. | 
| arrays\$1zip(a1, a2, ...) | N번째 구문에 입력 배열의 모든 N번째 값이 포함된 병합된 구조체 배열을 반환합니다. | 
| flatten(arrayOfArrays) | 배열의 배열을 단일 배열로 변환합니다. | 
| get(array, index) | 지정된 (0 기반) 인덱스에서 배열의 요소를 반환합니다. 인덱스가 배열 경계 외부를 가리키는 경우 이 함수는 NULL을 반환합니다. | 
| sequence(start, stop, step) | start부터 stop(끝 값 포함)까지 step만큼 증가하는 요소 배열을 생성합니다. 반환되는 요소의 유형은 인수 표현식의 유형과 동일합니다. 지원되는 유형은 byte, short, integer, long, date, timestamp입니다. start 및 stop 표현식은 동일한 유형으로 확인되어야 합니다. start 및 stop 표현식이 'date' 또는 'timestamp' 유형으로 확인되면 step 표현식은 'interval', 'year-month interval' 또는 'day-time interval' 유형으로 확인되어야 하며, 그렇지 않으면 start 및 stop 표현식과 동일한 유형으로 확인되어야 합니다. | 
| shuffle(array) | 지정된 배열의 임의 순열을 반환합니다. | 
| slice(x, start, length) | 지정된 길이의 인덱스 시작(배열 인덱스는 1에서 시작하거나 시작이 음수인 경우 끝에서 시작)부터 시작하는 배열 x의 부분 배열을 추출합니다. | 
| sort\$1array(array[, ascendingOrder]) | 배열 요소의 자연 순서에 따라 입력 배열을 오름차순 또는 내림차순으로 정렬합니다. NaN은 이중/부동 소수점 유형에 대한 비NaN 요소보다 큽니다. Null 요소는 반환된 배열의 시작 부분에 오름차순으로 또는 반환된 배열의 끝에 내림차순으로 배치됩니다. | 

**예시**

```
-- array
SELECT array(1, 2, 3);
+--------------+
|array(1, 2, 3)|
+--------------+
|     [1, 2, 3]|
+--------------+
-- array_append
SELECT array_append(array('b', 'd', 'c', 'a'), 'd');
+----------------------------------+
|array_append(array(b, d, c, a), d)|
+----------------------------------+
|                   [b, d, c, a, d]|
+----------------------------------+
SELECT array_append(array(1, 2, 3, null), null);
+----------------------------------------+
|array_append(array(1, 2, 3, NULL), NULL)|
+----------------------------------------+
|                    [1, 2, 3, NULL, N...|
+----------------------------------------+
SELECT array_append(CAST(null as Array<Int>), 2);
+---------------------+
|array_append(NULL, 2)|
+---------------------+
|                 NULL|
+---------------------+
-- array_compact
SELECT array_compact(array(1, 2, 3, null));
+-----------------------------------+
|array_compact(array(1, 2, 3, NULL))|
+-----------------------------------+
|                          [1, 2, 3]|
+-----------------------------------+
SELECT array_compact(array("a", "b", "c"));
+-----------------------------+
|array_compact(array(a, b, c))|
+-----------------------------+
|                    [a, b, c]|
+-----------------------------+
-- array_contains
SELECT array_contains(array(1, 2, 3), 2);
+---------------------------------+
|array_contains(array(1, 2, 3), 2)|
+---------------------------------+
|                             true|
+---------------------------------+
-- array_distinct
SELECT array_distinct(array(1, 2, 3, null, 3));
+---------------------------------------+
|array_distinct(array(1, 2, 3, NULL, 3))|
+---------------------------------------+
|                        [1, 2, 3, NULL]|
+---------------------------------------+
-- array_except
SELECT array_except(array(1, 2, 3), array(1, 3, 5));
+--------------------------------------------+
|array_except(array(1, 2, 3), array(1, 3, 5))|
+--------------------------------------------+
|                                         [2]|
+--------------------------------------------+
-- array_insert
SELECT array_insert(array(1, 2, 3, 4), 5, 5);
+-------------------------------------+
|array_insert(array(1, 2, 3, 4), 5, 5)|
+-------------------------------------+
|                      [1, 2, 3, 4, 5]|
+-------------------------------------+
SELECT array_insert(array(5, 4, 3, 2), -1, 1);
+--------------------------------------+
|array_insert(array(5, 4, 3, 2), -1, 1)|
+--------------------------------------+
|                       [5, 4, 3, 2, 1]|
+--------------------------------------+
SELECT array_insert(array(5, 3, 2, 1), -4, 4);
+--------------------------------------+
|array_insert(array(5, 3, 2, 1), -4, 4)|
+--------------------------------------+
|                       [5, 4, 3, 2, 1]|
+--------------------------------------+
-- array_intersect
SELECT array_intersect(array(1, 2, 3), array(1, 3, 5));
+-----------------------------------------------+
|array_intersect(array(1, 2, 3), array(1, 3, 5))|
+-----------------------------------------------+
|                                         [1, 3]|
+-----------------------------------------------+
-- array_join
SELECT array_join(array('hello', 'world'), ' ');
+----------------------------------+
|array_join(array(hello, world),  )|
+----------------------------------+
|                       hello world|
+----------------------------------+
SELECT array_join(array('hello', null ,'world'), ' ');
+----------------------------------------+
|array_join(array(hello, NULL, world),  )|
+----------------------------------------+
|                             hello world|
+----------------------------------------+
SELECT array_join(array('hello', null ,'world'), ' ', ',');
+-------------------------------------------+
|array_join(array(hello, NULL, world),  , ,)|
+-------------------------------------------+
|                              hello , world|
+-------------------------------------------+
-- array_max
SELECT array_max(array(1, 20, null, 3));
+--------------------------------+
|array_max(array(1, 20, NULL, 3))|
+--------------------------------+
|                              20|
+--------------------------------+
-- array_min
SELECT array_min(array(1, 20, null, 3));
+--------------------------------+
|array_min(array(1, 20, NULL, 3))|
+--------------------------------+
|                               1|
+--------------------------------+
-- array_position
SELECT array_position(array(312, 773, 708, 708), 708);
+----------------------------------------------+
|array_position(array(312, 773, 708, 708), 708)|
+----------------------------------------------+
|                                             3|
+----------------------------------------------+
SELECT array_position(array(312, 773, 708, 708), 414);
+----------------------------------------------+
|array_position(array(312, 773, 708, 708), 414)|
+----------------------------------------------+
|                                             0|
+----------------------------------------------+
-- array_prepend
SELECT array_prepend(array('b', 'd', 'c', 'a'), 'd');
+-----------------------------------+
|array_prepend(array(b, d, c, a), d)|
+-----------------------------------+
|                    [d, b, d, c, a]|
+-----------------------------------+
SELECT array_prepend(array(1, 2, 3, null), null);
+-----------------------------------------+
|array_prepend(array(1, 2, 3, NULL), NULL)|
+-----------------------------------------+
|                     [NULL, 1, 2, 3, N...|
+-----------------------------------------+
SELECT array_prepend(CAST(null as Array<Int>), 2);
+----------------------+
|array_prepend(NULL, 2)|
+----------------------+
|                  NULL|
+----------------------+
-- array_remove
SELECT array_remove(array(1, 2, 3, null, 3), 3);
+----------------------------------------+
|array_remove(array(1, 2, 3, NULL, 3), 3)|
+----------------------------------------+
|                            [1, 2, NULL]|
+----------------------------------------+
-- array_repeat
SELECT array_repeat('123', 2);
+--------------------+
|array_repeat(123, 2)|
+--------------------+
|          [123, 123]|
+--------------------+
-- array_union
SELECT array_union(array(1, 2, 3), array(1, 3, 5));
+-------------------------------------------+
|array_union(array(1, 2, 3), array(1, 3, 5))|
+-------------------------------------------+
|                               [1, 2, 3, 5]|
+-------------------------------------------+
-- arrays_overlap
SELECT arrays_overlap(array(1, 2, 3), array(3, 4, 5));
+----------------------------------------------+
|arrays_overlap(array(1, 2, 3), array(3, 4, 5))|
+----------------------------------------------+
|                                          true|
+----------------------------------------------+
-- arrays_zip
SELECT arrays_zip(array(1, 2, 3), array(2, 3, 4));
+------------------------------------------+
|arrays_zip(array(1, 2, 3), array(2, 3, 4))|
+------------------------------------------+
|                      [{1, 2}, {2, 3}, ...|
+------------------------------------------+
SELECT arrays_zip(array(1, 2), array(2, 3), array(3, 4));
+-------------------------------------------------+
|arrays_zip(array(1, 2), array(2, 3), array(3, 4))|
+-------------------------------------------------+
|                             [{1, 2, 3}, {2, 3...|
+-------------------------------------------------+
-- flatten
SELECT flatten(array(array(1, 2), array(3, 4)));
+----------------------------------------+
|flatten(array(array(1, 2), array(3, 4)))|
+----------------------------------------+
|                            [1, 2, 3, 4]|
+----------------------------------------+
-- get
SELECT get(array(1, 2, 3), 0);
+----------------------+
|get(array(1, 2, 3), 0)|
+----------------------+
|                     1|
+----------------------+
SELECT get(array(1, 2, 3), 3);
+----------------------+
|get(array(1, 2, 3), 3)|
+----------------------+
|                  NULL|
+----------------------+
SELECT get(array(1, 2, 3), -1);
+-----------------------+
|get(array(1, 2, 3), -1)|
+-----------------------+
|                   NULL|
+-----------------------+
-- sequence
SELECT sequence(1, 5);
+---------------+
| sequence(1, 5)|
+---------------+
|[1, 2, 3, 4, 5]|
+---------------+
SELECT sequence(5, 1);
+---------------+
| sequence(5, 1)|
+---------------+
|[5, 4, 3, 2, 1]|
+---------------+
SELECT sequence(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+----------------------------------------------------------------------+
|sequence(to_date(2018-01-01), to_date(2018-03-01), INTERVAL '1' MONTH)|
+----------------------------------------------------------------------+
|                                                  [2018-01-01, 2018...|
+----------------------------------------------------------------------+
SELECT sequence(to_date('2018-01-01'), to_date('2018-03-01'), interval '0-1' year to month);
+--------------------------------------------------------------------------------+
|sequence(to_date(2018-01-01), to_date(2018-03-01), INTERVAL '0-1' YEAR TO MONTH)|
+--------------------------------------------------------------------------------+
|                                                            [2018-01-01, 2018...|
+--------------------------------------------------------------------------------+
-- shuffle
SELECT shuffle(array(1, 20, 3, 5));
+---------------------------+
|shuffle(array(1, 20, 3, 5))|
+---------------------------+
|              [5, 1, 20, 3]|
+---------------------------+
SELECT shuffle(array(1, 20, null, 3));
+------------------------------+
|shuffle(array(1, 20, NULL, 3))|
+------------------------------+
|              [1, NULL, 20, 3]|
+------------------------------+
-- slice
SELECT slice(array(1, 2, 3, 4), 2, 2);
+------------------------------+
|slice(array(1, 2, 3, 4), 2, 2)|
+------------------------------+
|                        [2, 3]|
+------------------------------+
SELECT slice(array(1, 2, 3, 4), -2, 2);
+-------------------------------+
|slice(array(1, 2, 3, 4), -2, 2)|
+-------------------------------+
|                         [3, 4]|
+-------------------------------+
-- sort_array
SELECT sort_array(array('b', 'd', null, 'c', 'a'), true);
+-----------------------------------------+
|sort_array(array(b, d, NULL, c, a), true)|
+-----------------------------------------+
|                       [NULL, a, b, c, d]|
+-----------------------------------------+
```

#### 윈도우 함수
<a name="supported-sql-window"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

window 함수는 윈도우라고 하는 행 그룹에서 작동하며 행 그룹을 기반으로 각 행의 반환 값을 계산합니다. window 함수는 이동 평균 계산, 누적 통계 계산 또는 현재 행의 상대 위치가 지정된 행 값에 액세스와 같은 작업을 처리하는 데 유용합니다.

**구문** 

```
window_function [ nulls_option ] OVER ( [ { PARTITION | DISTRIBUTE } BY partition_col_name = partition_col_val ( [ , ... ] ) ] { ORDER | SORT } BY expression [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [ , ... ] [ window_frame ] ) 
```

**파라미터** 
+ 

  window\$1function 

  순위 함수 

  구문: `RANK | DENSE_RANK | PERCENT_RANK | NTILE | ROW_NUMBER `

  분석 함수 

  구문: `CUME_DIST | LAG | LEAD | NTH_VALUE | FIRST_VALUE | LAST_VALUE `

  집계 함수 

  구문: `MAX | MIN | COUNT | SUM | AVG | ... `
+ `nulls_option` - window 함수를 평가할 때 null 값을 건너뛸지 여부를 지정합니다. RESPECT NULLS는 null 값을 건너뛰지 않음을, IGNORE NULLS는 건너뜀을 의미합니다. 지정하지 않으면 기본값은 RESPECT NULLS입니다.

  구문: `{ IGNORE | RESPECT } NULLS `

  참고: `Only LAG` \$1 `LEAD` \$1 `NTH_VALUE` \$1 `FIRST_VALUE` \$1 `LAST_VALUE`는 `IGNORE NULLS`와 함께 사용할 수 있습니다.
+ `window_frame` - 윈도우를 시작할 행과 윈도우를 종료할 위치를 지정합니다.

  구문: `{ RANGE | ROWS } { frame_start | BETWEEN frame_start AND frame_end }` 

  frame\$1start 및 frame\$1end의 구문은 다음과 같습니다.

  구문: `UNBOUNDED PRECEDING | offset PRECEDING | CURRENT ROW | offset FOLLOWING | UNBOUNDED FOLLOWING `

  offset: 현재 행의 위치에서 오프셋을 지정합니다.

  **참고** frame\$1end를 생략하면 기본적으로 CURRENT ROW로 설정됩니다.

**예시**

```
CREATE TABLE employees (name STRING, dept STRING, salary INT, age INT);
INSERT INTO employees VALUES ("Lisa", "Sales", 10000, 35);
INSERT INTO employees VALUES ("Evan", "Sales", 32000, 38);
INSERT INTO employees VALUES ("Fred", "Engineering", 21000, 28);
INSERT INTO employees VALUES ("Alex", "Sales", 30000, 33);
INSERT INTO employees VALUES ("Tom", "Engineering", 23000, 33);
INSERT INTO employees VALUES ("Jane", "Marketing", 29000, 28);
INSERT INTO employees VALUES ("Jeff", "Marketing", 35000, 38);
INSERT INTO employees VALUES ("Paul", "Engineering", 29000, 23);
INSERT INTO employees VALUES ("Chloe", "Engineering", 23000, 25);
SELECT * FROM employees;
+-----+-----------+------+-----+
| name|       dept|salary|  age|
+-----+-----------+------+-----+
|Chloe|Engineering| 23000|   25|
| Fred|Engineering| 21000|   28|
| Paul|Engineering| 29000|   23|
|Helen|  Marketing| 29000|   40|
|  Tom|Engineering| 23000|   33|
| Jane|  Marketing| 29000|   28|
| Jeff|  Marketing| 35000|   38|
| Evan|      Sales| 32000|   38|
| Lisa|      Sales| 10000|   35|
| Alex|      Sales| 30000|   33|
+-----+-----------+------+-----+
SELECT name, dept, salary, RANK() OVER (PARTITION BY dept ORDER BY salary) AS rank FROM employees;
+-----+-----------+------+----+
| name|       dept|salary|rank|
+-----+-----------+------+----+
| Lisa|      Sales| 10000|   1|
| Alex|      Sales| 30000|   2|
| Evan|      Sales| 32000|   3|
| Fred|Engineering| 21000|   1|
|  Tom|Engineering| 23000|   2|
|Chloe|Engineering| 23000|   2|
| Paul|Engineering| 29000|   4|
|Helen|  Marketing| 29000|   1|
| Jane|  Marketing| 29000|   1|
| Jeff|  Marketing| 35000|   3|
+-----+-----------+------+----+
SELECT name, dept, salary, DENSE_RANK() OVER (PARTITION BY dept ORDER BY salary ROWS BETWEEN
UNBOUNDED PRECEDING AND CURRENT ROW) AS dense_rank FROM employees;
+-----+-----------+------+----------+
| name|       dept|salary|dense_rank|
+-----+-----------+------+----------+
| Lisa|      Sales| 10000|         1|
| Alex|      Sales| 30000|         2|
| Evan|      Sales| 32000|         3|
| Fred|Engineering| 21000|         1|
|  Tom|Engineering| 23000|         2|
|Chloe|Engineering| 23000|         2|
| Paul|Engineering| 29000|         3|
|Helen|  Marketing| 29000|         1|
| Jane|  Marketing| 29000|         1|
| Jeff|  Marketing| 35000|         2|
+-----+-----------+------+----------+
SELECT name, dept, age, CUME_DIST() OVER (PARTITION BY dept ORDER BY age
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cume_dist FROM employees;
+-----+-----------+------+------------------+
| name|       dept|age   |         cume_dist|
+-----+-----------+------+------------------+
| Alex|      Sales|    33|0.3333333333333333|
| Lisa|      Sales|    35|0.6666666666666666|
| Evan|      Sales|    38|               1.0|
| Paul|Engineering|    23|              0.25|
|Chloe|Engineering|    25|              0.75|
| Fred|Engineering|    28|              0.25|
|  Tom|Engineering|    33|               1.0|
| Jane|  Marketing|    28|0.3333333333333333|
| Jeff|  Marketing|    38|0.6666666666666666|
|Helen|  Marketing|    40|               1.0|
+-----+-----------+------+------------------+
SELECT name, dept, salary, MIN(salary) OVER (PARTITION BY dept ORDER BY salary) AS min
FROM employees;
+-----+-----------+------+-----+
| name|       dept|salary|  min|
+-----+-----------+------+-----+
| Lisa|      Sales| 10000|10000|
| Alex|      Sales| 30000|10000|
| Evan|      Sales| 32000|10000|
|Helen|  Marketing| 29000|29000|
| Jane|  Marketing| 29000|29000|
| Jeff|  Marketing| 35000|29000|
| Fred|Engineering| 21000|21000|
|  Tom|Engineering| 23000|21000|
|Chloe|Engineering| 23000|21000|
| Paul|Engineering| 29000|21000|
+-----+-----------+------+-----+
SELECT name, salary,
LAG(salary) OVER (PARTITION BY dept ORDER BY salary) AS lag,
LEAD(salary, 1, 0) OVER (PARTITION BY dept ORDER BY salary) AS lead
FROM employees;
+-----+-----------+------+-----+-----+
| name|       dept|salary|  lag| lead|
+-----+-----------+------+-----+-----+
| Lisa|      Sales| 10000|NULL |30000|
| Alex|      Sales| 30000|10000|32000|
| Evan|      Sales| 32000|30000|    0|
| Fred|Engineering| 21000| NULL|23000|
|Chloe|Engineering| 23000|21000|23000|
|  Tom|Engineering| 23000|23000|29000|
| Paul|Engineering| 29000|23000|    0|
|Helen|  Marketing| 29000| NULL|29000|
| Jane|  Marketing| 29000|29000|35000|
| Jeff|  Marketing| 35000|29000|    0|
+-----+-----------+------+-----+-----+
SELECT id, v,
LEAD(v, 0) IGNORE NULLS OVER w lead,
LAG(v, 0) IGNORE NULLS OVER w lag,
NTH_VALUE(v, 2) IGNORE NULLS OVER w nth_value,
FIRST_VALUE(v) IGNORE NULLS OVER w first_value,
LAST_VALUE(v) IGNORE NULLS OVER w last_value
FROM test_ignore_null
WINDOW w AS (ORDER BY id)
ORDER BY id;
+--+----+----+----+---------+-----------+----------+
|id|   v|lead| lag|nth_value|first_value|last_value|
+--+----+----+----+---------+-----------+----------+
| 0|NULL|NULL|NULL|     NULL|       NULL|      NULL|
| 1|   x|   x|   x|     NULL|          x|         x|
| 2|NULL|NULL|NULL|     NULL|          x|         x|
| 3|NULL|NULL|NULL|     NULL|          x|         x|
| 4|   y|   y|   y|        y|          x|         y|
| 5|NULL|NULL|NULL|        y|          x|         y|
| 6|   z|   z|   z|        y|          x|         z|
| 7|   v|   v|   v|        y|          x|         v|
| 8|NULL|NULL|NULL|        y|          x|         v|
+--+----+----+----+---------+-----------+----------+
```

#### 변환 함수
<a name="supported-sql-conversion"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).


****  

| 함수 | 설명 | 
| --- | --- | 
| bigint(expr) | `expr` 값을 대상 데이터 유형 `bigint`로 캐스팅합니다. | 
| binary(expr) | `expr` 값을 대상 데이터 유형 `binary`로 캐스팅합니다. | 
| boolean(expr) | `expr` 값을 대상 데이터 유형 `boolean`으로 캐스팅합니다. | 
| cast(expr AS type) | `expr` 값을 대상 데이터 유형 `type`으로 캐스팅합니다. | 
| date(expr) | `expr` 값을 대상 데이터 유형 `date`로 캐스팅합니다. | 
| decimal(expr) | `expr` 값을 대상 데이터 유형 `decimal`로 캐스팅합니다. | 
| double(expr) | `expr` 값을 대상 데이터 유형 `double`로 캐스팅합니다. | 
| float(expr) | `expr` 값을 대상 데이터 유형 `float`으로 캐스팅합니다. | 
| int(expr) | `expr` 값을 대상 데이터 유형 `int`로 캐스팅합니다. | 
| smallint(expr) | `expr` 값을 대상 데이터 유형 `smallint`로 캐스팅합니다. | 
| string(expr) | `expr` 값을 대상 데이터 유형 `string`으로 캐스팅합니다. | 
| timestamp(expr) | `expr` 값을 대상 데이터 유형 `timestamp`로 캐스팅합니다. | 
| tinyint(expr) | `expr` 값을 대상 데이터 유형 `tinyint`로 캐스팅합니다. | 

**예시**

```
-- cast
SELECT cast(field as int);
+---------------+
|CAST(field AS INT)|
+---------------+
|             10|
+---------------+
```

#### 조건자 함수
<a name="supported-sql-predicate"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).


****  

| 함수 | 설명 | 
| --- | --- | 
| \$1 expr | 논리 not. | 
| expr1 < expr2 | `expr1`이 `expr2`보다 작으면 true를 반환합니다. | 
| expr1 <= expr2 | `expr1`이 `expr2`보다 작거나 같으면 true를 반환합니다. | 
| expr1 <=> expr2 | null이 아닌 피연산자에 대해 EQUAL(=) 연산자와 동일한 결과를 반환하지만 둘 다 null이면 true, 둘 중 하나가 null이면 false를 반환합니다. | 
| expr1 = expr2 | `expr1`이 `expr2`와 같으면 true를 반환하고 그렇지 않으면 false를 반환합니다. | 
| expr1 == expr2 | `expr1`이 `expr2`와 같으면 true를 반환하고 그렇지 않으면 false를 반환합니다. | 
| expr1 > expr2 | `expr1`이 `expr2`보다 큰 경우 true를 반환합니다. | 
| expr1 >= expr2 | `expr1`이 `expr2`보다 크거나 같으면 true를 반환합니다. | 
| expr1 and expr2 | 논리적 AND | 
| str ilike pattern[ ESCAPE escape] | str이 대소문자를 구분하지 않고 `escape`를 포함한 `pattern`과 일치하면 true를 반환하고, 인수가 null이면 null을 반환하고, 그렇지 않으면 false를 반환합니다. | 
| expr1 in(expr2, expr3, ...) | `expr`가 임의의 valN과 같으면 true를 반환합니다. | 
| isnan(expr) | `expr`가 NaN이면 true를 반환하고 그렇지 않으면 false를 반환합니다. | 
| isnotnull(expr) | `expr`가 null이 아니면 true를 반환하고 그렇지 않으면 false를 반환합니다. | 
| isnull(expr) | `expr`가 null이면 true를 반환하고 그렇지 않으면 false를 반환합니다. | 
| str like pattern[ ESCAPE escape] | str이 `pattern`과 `escape`가 일치하면 true를 반환하고, 인수가 null이면 null을 반환하고, 그렇지 않으면 false를 반환합니다. | 
| not expr | 논리 not. | 
| expr1 or expr2 | 논리적 OR | 
| regexp(str, regexp) | `str`이 `regexp`와 일치하면 true를 반환하고, 그렇지 않으면 false를 반환합니다. | 
| regexp\$1like(str, regexp) | `str`이 `regexp`와 일치하면 true를 반환하고, 그렇지 않으면 false를 반환합니다. | 
| rlike(str, regexp) | `str`이 `regexp`와 일치하면 true를 반환하고, 그렇지 않으면 false를 반환합니다. | 

**예시**

```
-- !
SELECT ! true;
+----------+
|(NOT true)|
+----------+
|     false|
+----------+
SELECT ! false;
+-----------+
|(NOT false)|
+-----------+
|       true|
+-----------+
SELECT ! NULL;
+----------+
|(NOT NULL)|
+----------+
|      NULL|
+----------+
-- <
SELECT to_date('2009-07-30 04:17:52') < to_date('2009-07-30 04:17:52');
+-------------------------------------------------------------+
|(to_date(2009-07-30 04:17:52) < to_date(2009-07-30 04:17:52))|
+-------------------------------------------------------------+
|                                                        false|
+-------------------------------------------------------------+
SELECT to_date('2009-07-30 04:17:52') < to_date('2009-08-01 04:17:52');
+-------------------------------------------------------------+
|(to_date(2009-07-30 04:17:52) < to_date(2009-08-01 04:17:52))|
+-------------------------------------------------------------+
|                                                         true|
+-------------------------------------------------------------+
SELECT 1 < NULL;
+----------+
|(1 < NULL)|
+----------+
|      NULL|
+----------+
-- <=
SELECT 2 <= 2;
+--------+
|(2 <= 2)|
+--------+
|    true|
+--------+
SELECT 1.0 <= '1';
+----------+
|(1.0 <= 1)|
+----------+
|      true|
+----------+
SELECT to_date('2009-07-30 04:17:52') <= to_date('2009-07-30 04:17:52');
+--------------------------------------------------------------+
|(to_date(2009-07-30 04:17:52) <= to_date(2009-07-30 04:17:52))|
+--------------------------------------------------------------+
|                                                          true|
+--------------------------------------------------------------+
SELECT to_date('2009-07-30 04:17:52') <= to_date('2009-08-01 04:17:52');
+--------------------------------------------------------------+
|(to_date(2009-07-30 04:17:52) <= to_date(2009-08-01 04:17:52))|
+--------------------------------------------------------------+
|                                                          true|
+--------------------------------------------------------------+
SELECT 1 <= NULL;
+-----------+
|(1 <= NULL)|
+-----------+
|       NULL|
+-----------+
-- <=>
SELECT 2 <=> 2;
+---------+
|(2 <=> 2)|
+---------+
|     true|
+---------+
SELECT 1 <=> '1';
+---------+
|(1 <=> 1)|
+---------+
|     true|
+---------+
SELECT true <=> NULL;
+---------------+
|(true <=> NULL)|
+---------------+
|          false|
+---------------+
SELECT NULL <=> NULL;
+---------------+
|(NULL <=> NULL)|
+---------------+
|           true|
+---------------+
-- =
SELECT 2 = 2;
+-------+
|(2 = 2)|
+-------+
|   true|
+-------+
SELECT 1 = '1';
+-------+
|(1 = 1)|
+-------+
|   true|
+-------+
SELECT true = NULL;
+-------------+
|(true = NULL)|
+-------------+
|         NULL|
+-------------+
SELECT NULL = NULL;
+-------------+
|(NULL = NULL)|
+-------------+
|         NULL|
+-------------+
-- ==
SELECT 2 == 2;
+-------+
|(2 = 2)|
+-------+
|   true|
+-------+
SELECT 1 == '1';
+-------+
|(1 = 1)|
+-------+
|   true|
+-------+
SELECT true == NULL;
+-------------+
|(true = NULL)|
+-------------+
|         NULL|
+-------------+
SELECT NULL == NULL;
+-------------+
|(NULL = NULL)|
+-------------+
|         NULL|
+-------------+
-- >
SELECT 2 > 1;
+-------+
|(2 > 1)|
+-------+
|   true|
+-------+
SELECT 2 > 1.1;
+-------+
|(2 > 1)|
+-------+
|   true|
+-------+
SELECT to_date('2009-07-30 04:17:52') > to_date('2009-07-30 04:17:52');
+-------------------------------------------------------------+
|(to_date(2009-07-30 04:17:52) > to_date(2009-07-30 04:17:52))|
+-------------------------------------------------------------+
|                                                        false|
+-------------------------------------------------------------+
SELECT to_date('2009-07-30 04:17:52') > to_date('2009-08-01 04:17:52');
+-------------------------------------------------------------+
|(to_date(2009-07-30 04:17:52) > to_date(2009-08-01 04:17:52))|
+-------------------------------------------------------------+
|                                                        false|
+-------------------------------------------------------------+
SELECT 1 > NULL;
+----------+
|(1 > NULL)|
+----------+
|      NULL|
+----------+
-- >=
SELECT 2 >= 1;
+--------+
|(2 >= 1)|
+--------+
|    true|
+--------+
SELECT 2.0 >= '2.1';
+------------+
|(2.0 >= 2.1)|
+------------+
|       false|
+------------+
SELECT to_date('2009-07-30 04:17:52') >= to_date('2009-07-30 04:17:52');
+--------------------------------------------------------------+
|(to_date(2009-07-30 04:17:52) >= to_date(2009-07-30 04:17:52))|
+--------------------------------------------------------------+
|                                                          true|
+--------------------------------------------------------------+
SELECT to_date('2009-07-30 04:17:52') >= to_date('2009-08-01 04:17:52');
+--------------------------------------------------------------+
|(to_date(2009-07-30 04:17:52) >= to_date(2009-08-01 04:17:52))|
+--------------------------------------------------------------+
|                                                         false|
+--------------------------------------------------------------+
SELECT 1 >= NULL;
+-----------+
|(1 >= NULL)|
+-----------+
|       NULL|
+-----------+
-- and
SELECT true and true;
+---------------+
|(true AND true)|
+---------------+
|           true|
+---------------+
SELECT true and false;
+----------------+
|(true AND false)|
+----------------+
|           false|
+----------------+
SELECT true and NULL;
+---------------+
|(true AND NULL)|
+---------------+
|           NULL|
+---------------+
SELECT false and NULL;
+----------------+
|(false AND NULL)|
+----------------+
|           false|
+----------------+
-- ilike
SELECT ilike('Wagon', '_Agon');
+-------------------+
|ilike(Wagon, _Agon)|
+-------------------+
|               true|
+-------------------+
SELECT '%SystemDrive%\Users\John' ilike '\%SystemDrive\%\\users%';
+--------------------------------------------------------+
|ilike(%SystemDrive%\Users\John, \%SystemDrive\%\\users%)|
+--------------------------------------------------------+
|                                                    true|
+--------------------------------------------------------+
SELECT '%SystemDrive%\\USERS\\John' ilike '\%SystemDrive\%\\\\Users%';
+--------------------------------------------------------+
|ilike(%SystemDrive%\USERS\John, \%SystemDrive\%\\Users%)|
+--------------------------------------------------------+
|                                                    true|
+--------------------------------------------------------+
SELECT '%SystemDrive%/Users/John' ilike '/%SYSTEMDrive/%//Users%' ESCAPE '/';
+--------------------------------------------------------+
|ilike(%SystemDrive%/Users/John, /%SYSTEMDrive/%//Users%)|
+--------------------------------------------------------+
|                                                    true|
+--------------------------------------------------------+
-- in
SELECT 1 in(1, 2, 3);
+----------------+
|(1 IN (1, 2, 3))|
+----------------+
|            true|
+----------------+
SELECT 1 in(2, 3, 4);
+----------------+
|(1 IN (2, 3, 4))|
+----------------+
|           false|
+----------------+
SELECT named_struct('a', 1, 'b', 2) in(named_struct('a', 1, 'b', 1), named_struct('a', 1, 'b', 3));
+----------------------------------------------------------------------------------+
|(named_struct(a, 1, b, 2) IN (named_struct(a, 1, b, 1), named_struct(a, 1, b, 3)))|
+----------------------------------------------------------------------------------+
|                                                                             false|
+----------------------------------------------------------------------------------+
SELECT named_struct('a', 1, 'b', 2) in(named_struct('a', 1, 'b', 2), named_struct('a', 1, 'b', 3));
+----------------------------------------------------------------------------------+
|(named_struct(a, 1, b, 2) IN (named_struct(a, 1, b, 2), named_struct(a, 1, b, 3)))|
+----------------------------------------------------------------------------------+
|                                                                              true|
+----------------------------------------------------------------------------------+
-- isnan
SELECT isnan(cast('NaN' as double));
+--------------------------+
|isnan(CAST(NaN AS DOUBLE))|
+--------------------------+
|                      true|
+--------------------------+
-- isnotnull
SELECT isnotnull(1);
+---------------+
|(1 IS NOT NULL)|
+---------------+
|           true|
+---------------+
-- isnull
SELECT isnull(1);
+-----------+
|(1 IS NULL)|
+-----------+
|      false|
+-----------+
-- like
SELECT like('Wagon', '_Agon');
+----------------+
|Wagon LIKE _Agon|
+----------------+
|            true|
+----------------+
-- not
SELECT not true;
+----------+
|(NOT true)|
+----------+
|     false|
+----------+
SELECT not false;
+-----------+
|(NOT false)|
+-----------+
|       true|
+-----------+
SELECT not NULL;
+----------+
|(NOT NULL)|
+----------+
|      NULL|
+----------+
-- or
SELECT true or false;
+---------------+
|(true OR false)|
+---------------+
|           true|
+---------------+
SELECT false or false;
+----------------+
|(false OR false)|
+----------------+
|           false|
+----------------+
SELECT true or NULL;
+--------------+
|(true OR NULL)|
+--------------+
|          true|
+--------------+
SELECT false or NULL;
+---------------+
|(false OR NULL)|
+---------------+
|           NULL|
+---------------+
```

#### 맵 함수
<a name="supported-sql-map"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).


****  

| 함수 | 설명 | 
| --- | --- | 
| element\$1at(array, index) | 지정된 (1 기반) 인덱스에서 배열의 요소를 반환합니다. | 
| element\$1at(map, key) | 지정된 키의 값을 반환합니다. 키가 맵에 포함되지 않은 경우 이 함수는 NULL을 반환합니다. | 
| map(key0, value0, key1, value1, ...) | 지정된 키/값 페어로 맵을 생성합니다. | 
| map\$1concat(map, ...) | 지정된 모든 맵의 합집합을 반환합니다. | 
| map\$1contains\$1key(map, key) | 맵에 키가 포함되어 있는 경우 true를 반환합니다. | 
| map\$1entries(map) | 지정된 맵에 있는 모든 항목의 정렬되지 않은 배열을 반환합니다. | 
| map\$1from\$1arrays(keys, values) | 지정된 키/값 배열 페어로 맵을 생성합니다. 키의 모든 요소는 null이 아니어야 합니다. | 
| map\$1from\$1entries(arrayOfEntries) | 지정된 항목 배열에서 생성된 맵을 반환합니다. | 
| map\$1keys(map) | 맵의 키가 포함된 정렬되지 않은 배열을 반환합니다. | 
| map\$1values(map) | 맵의 값이 포함된 정렬되지 않은 배열을 반환합니다. | 
| str\$1to\$1map(text[, pairDelim[, keyValueDelim]]) | 구분 기호를 사용하여 텍스트를 키/값 페어로 분할한 후 맵을 생성합니다. 기본 구분 기호는 `pairDelim`의 경우 ',', `keyValueDelim`의 경우 ':'입니다. `pairDelim`과 `keyValueDelim`은 모두 정규식으로 처리됩니다. | 
| try\$1element\$1at(array, index) | 지정된 (1 기반) 인덱스에서 배열의 요소를 반환합니다. 인덱스가 0이면 시스템에서 오류가 발생합니다. 인덱스가 0보다 작으면 마지막에서 첫 번째로 요소에 액세스합니다. 인덱스가 배열 길이를 초과하면 함수는 항상 NULL을 반환합니다. | 
| try\$1element\$1at(map, key) | 지정된 키의 값을 반환합니다. 키가 맵에 포함되지 않은 경우 이 함수는 항상 NULL을 반환합니다. | 

**예시**

```
-- element_at
SELECT element_at(array(1, 2, 3), 2);
+-----------------------------+
|element_at(array(1, 2, 3), 2)|
+-----------------------------+
|                            2|
+-----------------------------+
SELECT element_at(map(1, 'a', 2, 'b'), 2);
+------------------------------+
|element_at(map(1, a, 2, b), 2)|
+------------------------------+
|                             b|
+------------------------------+
-- map
SELECT map(1.0, '2', 3.0, '4');
+--------------------+
| map(1.0, 2, 3.0, 4)|
+--------------------+
|{1.0 -> 2, 3.0 -> 4}|
+--------------------+
-- map_concat
SELECT map_concat(map(1, 'a', 2, 'b'), map(3, 'c'));
+--------------------------------------+
|map_concat(map(1, a, 2, b), map(3, c))|
+--------------------------------------+
|                  {1 -> a, 2 -> b, ...|
+--------------------------------------+
-- map_contains_key
SELECT map_contains_key(map(1, 'a', 2, 'b'), 1);
+------------------------------------+
|map_contains_key(map(1, a, 2, b), 1)|
+------------------------------------+
|                                true|
+------------------------------------+
SELECT map_contains_key(map(1, 'a', 2, 'b'), 3);
+------------------------------------+
|map_contains_key(map(1, a, 2, b), 3)|
+------------------------------------+
|                               false|
+------------------------------------+
-- map_entries
SELECT map_entries(map(1, 'a', 2, 'b'));
+----------------------------+
|map_entries(map(1, a, 2, b))|
+----------------------------+
|            [{1, a}, {2, b}]|
+----------------------------+
-- map_from_arrays
SELECT map_from_arrays(array(1.0, 3.0), array('2', '4'));
+---------------------------------------------+
|map_from_arrays(array(1.0, 3.0), array(2, 4))|
+---------------------------------------------+
|                         {1.0 -> 2, 3.0 -> 4}|
+---------------------------------------------+
-- map_from_entries
SELECT map_from_entries(array(struct(1, 'a'), struct(2, 'b')));
+---------------------------------------------------+
|map_from_entries(array(struct(1, a), struct(2, b)))|
+---------------------------------------------------+
|                                   {1 -> a, 2 -> b}|
+---------------------------------------------------+
-- map_keys
SELECT map_keys(map(1, 'a', 2, 'b'));
+-------------------------+
|map_keys(map(1, a, 2, b))|
+-------------------------+
|                   [1, 2]|
+-------------------------+
-- map_values
SELECT map_values(map(1, 'a', 2, 'b'));
+---------------------------+
|map_values(map(1, a, 2, b))|
+---------------------------+
|                     [a, b]|
+---------------------------+
-- str_to_map
SELECT str_to_map('a:1,b:2,c:3', ',', ':');
+-----------------------------+
|str_to_map(a:1,b:2,c:3, ,, :)|
+-----------------------------+
|         {a -> 1, b -> 2, ...|
+-----------------------------+
SELECT str_to_map('a');
+-------------------+
|str_to_map(a, ,, :)|
+-------------------+
|        {a -> NULL}|
+-------------------+
-- try_element_at
SELECT try_element_at(array(1, 2, 3), 2);
+---------------------------------+
|try_element_at(array(1, 2, 3), 2)|
+---------------------------------+
|                                2|
+---------------------------------+
SELECT try_element_at(map(1, 'a', 2, 'b'), 2);
+----------------------------------+
|try_element_at(map(1, a, 2, b), 2)|
+----------------------------------+
|                                 b|
+----------------------------------+
```

#### 수학 함수
<a name="supported-sql-math"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).


****  

| 함수 | 설명 | 
| --- | --- | 
| expr1 % expr2 | `expr1`/`expr2` 뒤의 나머지 부분을 반환합니다. | 
| expr1 \$1 expr2 | `expr1`\$1`expr2`를 반환합니다. | 
| expr1 \$1 expr2 | `expr1`\$1`expr2`를 반환합니다. | 
| expr1 - expr2 | `expr1`-`expr2`를 반환합니다. | 
| expr1 / expr2 | `expr1`/`expr2`를 반환합니다. 항상 부동 소수점 분할을 수행합니다. | 
| abs(expr) | 값의 절대값을 반환합니다. | 
| acos(expr) | `java.lang.Math.acos`로 계산된 것처럼, `expr`의 역코사인(아크 코사인)을 반환합니다. | 
| acosh(expr) | `expr`의 역 하이퍼볼릭 코사인을 반환합니다. | 
| asin(expr) | `java.lang.Math.asin`으로 계산되는 것처럼 `expr`의 역사인(아크 사인)을 반환합니다. | 
| asinh(expr) | `expr`의 역 하이퍼볼릭 사인을 반환합니다. | 
| atan(expr) | `java.lang.Math.atan`으로 계산된 것처럼 `expr`의 역탄젠트(아크 탄젠트)를 반환합니다. | 
| atan2(exprY, exprX) | `java.lang.Math.atan2`로 계산된 것처럼 평면의 양수 x축과 좌표로 지정된 점(`exprX`, `exprY`) 사이의 각도를 라디안 단위로 반환합니다. | 
| atanh(expr) | `expr`의 역 하이퍼볼릭 탄젠트를 반환합니다. | 
| bin(expr) | 바이너리로 표시되는 long 값 `expr`의 문자열 표현을 반환합니다. | 
| bround(expr, d) | HALF\$1EVEN 반올림 모드를 사용하여 `d` 소수 자릿수로 반올림된 `expr`를 반환합니다. | 
| cbrt(expr) | `expr`의 세제곱근을 반환합니다. | 
| ceil(expr[, scale]) | 반올림 후 `expr`보다 작지 않은 가장 작은 숫자를 반환합니다. 반올림 동작을 제어하기 위해 선택적 `scale` 파라미터를 지정할 수 있습니다. | 
| ceiling(expr[, scale]) | 반올림 후 `expr`보다 작지 않은 가장 작은 숫자를 반환합니다. 반올림 동작을 제어하기 위해 선택적 `scale` 파라미터를 지정할 수 있습니다. | 
| conv(num, from\$1base, to\$1base) | `num`을 `from\$1base`에서 `to\$1base`로 변환합니다. | 
| cos(expr) | `java.lang.Math.cos`로 계산된 것처럼 `expr`의 코사인을 반환합니다. | 
| cosh(expr) | `java.lang.Math.cosh`로 계산된 것처럼 `expr`의 하이퍼볼릭 코사인을 반환합니다. | 
| cot(expr) | `1/java.lang.Math.tan`으로 계산된 것처럼 `expr`의 코탄젠트를 반환합니다. | 
| csc(expr) | `1/java.lang.Math.sin`으로 계산되는 것처럼 `expr`의 코시컨트를 반환합니다. | 
| degrees(expr) | 라디안을 도로 변환합니다. | 
| expr1 div expr2 | `expr1`을 `expr2`로 나눕니다. 피연산자가 NULL이거나 `expr2`가 0인 경우 NULL을 반환합니다. 결과는 long으로 캐스팅됩니다. | 
| e() | Euler의 번호 e를 반환합니다. | 
| exp(expr) | e를 `expr`의 출력으로 반환합니다. | 
| expm1(expr) - exp(`expr`)를 반환합니다. | 1 | 
| factorial(expr) | `expr`의 인수를 반환합니다. `expr`는 [0..20]입니다. 그렇지 않은 경우 null입니다. | 
| floor(expr[, scale]) | 반올림 후 `expr`보다 크지 않은 가장 큰 숫자를 반환합니다. 반올림 동작을 제어하기 위해 선택적 `scale` 파라미터를 지정할 수 있습니다. | 
| greatest(expr, ...) | null 값을 건너뛰면서 모든 파라미터의 가장 큰 값을 반환합니다. | 
| hex(expr) | `expr`를 16진수로 변환합니다. | 
| hypot(expr1, expr2) | sqrt(`expr1`\$1\$12 \$1 `expr2`\$1\$12)를 반환합니다. | 
| least(expr, ...) | null 값을 건너뛰면서 모든 파라미터의 가장 작은 값을 반환합니다. | 
| ln(expr) | `expr`의 자연 로그(밑 e)를 반환합니다. | 
| log(base, expr) | `base`와 함께 `expr`의 로그를 반환합니다. | 
| log10(expr) | base 10과 함께 `expr`의 로그를 반환합니다. | 
| log1p(expr) | log(1 \$1 `expr`)를 반환합니다. | 
| log2(expr) | base 2와 함께 `expr`의 로그를 반환합니다. | 
| expr1 mod expr2 | `expr1`/`expr2` 뒤의 나머지 부분을 반환합니다. | 
| negative(expr) | `expr`의 부호를 반전한 값을 반환합니다. | 
| pi() | pi를 반환합니다. | 
| pmod(expr1, expr2) | `expr1` mod `expr2`의 양수 값을 반환합니다. | 
| positive(expr) | `expr`의 값을 반환합니다. | 
| pow(expr1, expr2) | `expr1`을 `expr2`의 출력으로 제곱합니다. | 
| power(expr1, expr2) | `expr1`을 `expr2`의 출력으로 제곱합니다. | 
| radians(expr) | 각도를 라디안으로 변환합니다. | 
| rand([seed]) | [0, 1) 구간에 균일하게 값이 분포하는 독립적이고 동일하게 분포(i.i.d.)하는 임의의 값을 반환합니다. | 
| randn([seed]) | 표준 정규 분포에서 가져온 독립적이고 동일하게 분포(i.i.d.)하는 값이 있는 임의 값을 반환합니다. | 
| random([seed]) | [0, 1) 구간에 균일하게 값이 분포하는 독립적이고 동일하게 분포(i.i.d.)하는 임의의 값을 반환합니다. | 
| rint(expr) | 인수에 대한 값에서 가장 가깝고 수학 정수와 동일한 이중 값을 반환합니다. | 
| round(expr, d) | HALF\$1UP 반올림 모드를 사용하여 `d` 소수 자릿수로 반올림된 `expr`를 반환합니다. | 
| sec(expr) | `1/java.lang.Math.cos`로 계산된 것처럼 `expr`의 시컨트를 반환합니다. | 
| shiftleft(base, expr) | 비트 단위로 왼쪽 이동합니다. | 
| sign(expr) | `expr`이 음수, 0 또는 양수이므로 -1.0, 0.0 또는 1.0을 반환합니다. | 
| signum(expr) | `expr`이 음수, 0 또는 양수이므로 -1.0, 0.0 또는 1.0을 반환합니다. | 
| sin(expr) | `java.lang.Math.sin`으로 계산된 것처럼 `expr`의 사인을 반환합니다. | 
| sinh(expr) | `java.lang.Math.sinh`로 계산된 것처럼 `expr`의 하이퍼볼릭 사인을 반환합니다. | 
| sqrt(expr) | `expr`의 제곱근을 반환합니다. | 
| tan(expr) | `java.lang.Math.tan`으로 계산된 것처럼 `expr`의 탄젠트를 반환합니다. | 
| tanh(expr) | `java.lang.Math.tanh`로 계산된 것처럼 `expr`의 하이퍼볼릭 탄젠트를 반환합니다. | 
| try\$1add(expr1, expr2) | `expr1`과 `expr2`의 합계를 반환하며 오버플로 시 결과는 null입니다. 허용되는 입력 유형은 `\$1` 연산자와 동일합니다. | 
| try\$1divide(dividend, divisor) | `dividend`/`divisor`를 반환합니다. 항상 부동 소수점 분할을 수행합니다. `expr2`가 0인 경우 결과는 항상 null입니다. `dividend`는 숫자 또는 간격이어야 합니다. `divisor`는 숫자여야 합니다. | 
| try\$1multiply(expr1, expr2) | `expr1`\$1`expr2`를 반환하며 오버플로 시 결과는 null입니다. 허용되는 입력 유형은 `\$1` 연산자와 동일합니다. | 
| try\$1subtract(expr1, expr2) | `expr1`-`expr2`를 반환하며 오버플로 시 결과는 null입니다. 허용되는 입력 유형은 `-` 연산자와 동일합니다. | 
| unhex(expr) | 16진수 `expr`를 이진수로 변환합니다. | 
| width\$1bucket(value, min\$1value, max\$1value, num\$1bucket) | `min\$1value`\$1`max\$1value` 범위의 `num\$1bucket` 버킷이 있는 등가 히스토그램에서 `value`가 할당될 버킷 번호를 반환합니다. | 

**예시**

```
-- %
SELECT 2 % 1.8;
+---------+
|(2 % 1.8)|
+---------+
|      0.2|
+---------+
SELECT MOD(2, 1.8);
+-----------+
|mod(2, 1.8)|
+-----------+
|        0.2|
+-----------+
-- *
SELECT 2 * 3;
+-------+
|(2 * 3)|
+-------+
|      6|
+-------+
-- +
SELECT 1 + 2;
+-------+
|(1 + 2)|
+-------+
|      3|
+-------+
-- -
SELECT 2 - 1;
+-------+
|(2 - 1)|
+-------+
|      1|
+-------+
-- /
SELECT 3 / 2;
+-------+
|(3 / 2)|
+-------+
|    1.5|
+-------+
SELECT 2L / 2L;
+-------+
|(2 / 2)|
+-------+
|    1.0|
+-------+
-- abs
SELECT abs(-1);
+-------+
|abs(-1)|
+-------+
|      1|
+-------+
SELECT abs(INTERVAL -'1-1' YEAR TO MONTH);
+----------------------------------+
|abs(INTERVAL '-1-1' YEAR TO MONTH)|
+----------------------------------+
|              INTERVAL '1-1' YE...|
+----------------------------------+
-- acos
SELECT acos(1);
+-------+
|ACOS(1)|
+-------+
|    0.0|
+-------+
SELECT acos(2);
+-------+
|ACOS(2)|
+-------+
|    NaN|
+-------+
-- acosh
SELECT acosh(1);
+--------+
|ACOSH(1)|
+--------+
|     0.0|
+--------+
SELECT acosh(0);
+--------+
|ACOSH(0)|
+--------+
|     NaN|
+--------+
-- asin
SELECT asin(0);
+-------+
|ASIN(0)|
+-------+
|    0.0|
+-------+
SELECT asin(2);
+-------+
|ASIN(2)|
+-------+
|    NaN|
+-------+
-- asinh
SELECT asinh(0);
+--------+
|ASINH(0)|
+--------+
|     0.0|
+--------+
-- atan
SELECT atan(0);
+-------+
|ATAN(0)|
+-------+
|    0.0|
+-------+
-- atan2
SELECT atan2(0, 0);
+-----------+
|ATAN2(0, 0)|
+-----------+
|        0.0|
+-----------+
-- atanh
SELECT atanh(0);
+--------+
|ATANH(0)|
+--------+
|     0.0|
+--------+
SELECT atanh(2);
+--------+
|ATANH(2)|
+--------+
|     NaN|
+--------+
-- bin
SELECT bin(13);
+-------+
|bin(13)|
+-------+
|   1101|
+-------+
SELECT bin(-13);
+--------------------+
|            bin(-13)|
+--------------------+
|11111111111111111...|
+--------------------+
SELECT bin(13.3);
+---------+
|bin(13.3)|
+---------+
|     1101|
+---------+
-- bround
SELECT bround(2.5, 0);
+--------------+
|bround(2.5, 0)|
+--------------+
|             2|
+--------------+
SELECT bround(25, -1);
+--------------+
|bround(25, -1)|
+--------------+
|            20|
+--------------+
-- cbrt
SELECT cbrt(27.0);
+----------+
|CBRT(27.0)|
+----------+
|       3.0|
+----------+
-- ceil
SELECT ceil(-0.1);
+----------+
|CEIL(-0.1)|
+----------+
|         0|
+----------+
SELECT ceil(5);
+-------+
|CEIL(5)|
+-------+
|      5|
+-------+
SELECT ceil(3.1411, 3);
+---------------+
|ceil(3.1411, 3)|
+---------------+
|          3.142|
+---------------+
SELECT ceil(3.1411, -3);
+----------------+
|ceil(3.1411, -3)|
+----------------+
|            1000|
+----------------+
-- ceiling
SELECT ceiling(-0.1);
+-------------+
|ceiling(-0.1)|
+-------------+
|            0|
+-------------+
SELECT ceiling(5);
+----------+
|ceiling(5)|
+----------+
|         5|
+----------+
SELECT ceiling(3.1411, 3);
+------------------+
|ceiling(3.1411, 3)|
+------------------+
|             3.142|
+------------------+
SELECT ceiling(3.1411, -3);
+-------------------+
|ceiling(3.1411, -3)|
+-------------------+
|               1000|
+-------------------+
-- conv
SELECT conv('100', 2, 10);
+----------------+
|conv(100, 2, 10)|
+----------------+
|               4|
+----------------+
SELECT conv(-10, 16, -10);
+------------------+
|conv(-10, 16, -10)|
+------------------+
|               -16|
+------------------+
-- cos
SELECT cos(0);
+------+
|COS(0)|
+------+
|   1.0|
+------+
-- cosh
SELECT cosh(0);
+-------+
|COSH(0)|
+-------+
|    1.0|
+-------+
-- cot
SELECT cot(1);
+------------------+
|            COT(1)|
+------------------+
|0.6420926159343306|
+------------------+
-- csc
SELECT csc(1);
+------------------+
|            CSC(1)|
+------------------+
|1.1883951057781212|
+------------------+
-- degrees
SELECT degrees(3.141592653589793);
+--------------------------+
|DEGREES(3.141592653589793)|
+--------------------------+
|                     180.0|
+--------------------------+
-- div
SELECT 3 div 2;
+---------+
|(3 div 2)|
+---------+
|        1|
+---------+
SELECT INTERVAL '1-1' YEAR TO MONTH div INTERVAL '-1' MONTH;
+------------------------------------------------------+
|(INTERVAL '1-1' YEAR TO MONTH div INTERVAL '-1' MONTH)|
+------------------------------------------------------+
|                                                   -13|
+------------------------------------------------------+
-- e
SELECT e();
+-----------------+
|              E()|
+-----------------+
|2.718281828459045|
+-----------------+
-- exp
SELECT exp(0);
+------+
|EXP(0)|
+------+
|   1.0|
+------+
-- expm1
SELECT expm1(0);
+--------+
|EXPM1(0)|
+--------+
|     0.0|
+--------+
-- factorial
SELECT factorial(5);
+------------+
|factorial(5)|
+------------+
|         120|
+------------+
-- floor
SELECT floor(-0.1);
+-----------+
|FLOOR(-0.1)|
+-----------+
|         -1|
+-----------+
SELECT floor(5);
+--------+
|FLOOR(5)|
+--------+
|       5|
+--------+
SELECT floor(3.1411, 3);
+----------------+
|floor(3.1411, 3)|
+----------------+
|           3.141|
+----------------+
SELECT floor(3.1411, -3);
+-----------------+
|floor(3.1411, -3)|
+-----------------+
|                0|
+-----------------+
-- greatest
SELECT greatest(10, 9, 2, 4, 3);
+------------------------+
|greatest(10, 9, 2, 4, 3)|
+------------------------+
|                      10|
+------------------------+
-- hex
SELECT hex(17);
+-------+
|hex(17)|
+-------+
|     11|
+-------+
SELECT hex('SQL');
+------------------+
|    hex(SQL)|
+------------------+
|53514C|
+------------------+
-- hypot
SELECT hypot(3, 4);
+-----------+
|HYPOT(3, 4)|
+-----------+
|        5.0|
+-----------+
-- least
SELECT least(10, 9, 2, 4, 3);
+---------------------+
|least(10, 9, 2, 4, 3)|
+---------------------+
|                    2|
+---------------------+
-- ln
SELECT ln(1);
+-----+
|ln(1)|
+-----+
|  0.0|
+-----+
-- log
SELECT log(10, 100);
+------------+
|LOG(10, 100)|
+------------+
|         2.0|
+------------+
-- log10
SELECT log10(10);
+---------+
|LOG10(10)|
+---------+
|      1.0|
+---------+
-- log1p
SELECT log1p(0);
+--------+
|LOG1P(0)|
+--------+
|     0.0|
+--------+
-- log2
SELECT log2(2);
+-------+
|LOG2(2)|
+-------+
|    1.0|
+-------+
-- mod
SELECT 2 % 1.8;
+---------+
|(2 % 1.8)|
+---------+
|      0.2|
+---------+
SELECT MOD(2, 1.8);
+-----------+
|mod(2, 1.8)|
+-----------+
|        0.2|
+-----------+
-- negative
SELECT negative(1);
+-----------+
|negative(1)|
+-----------+
|         -1|
+-----------+
-- pi
SELECT pi();
+-----------------+
|             PI()|
+-----------------+
|3.141592653589793|
+-----------------+
-- pmod
SELECT pmod(10, 3);
+-----------+
|pmod(10, 3)|
+-----------+
|          1|
+-----------+
SELECT pmod(-10, 3);
+------------+
|pmod(-10, 3)|
+------------+
|           2|
+------------+
-- positive
SELECT positive(1);
+-----+
|(+ 1)|
+-----+
|    1|
+-----+
-- pow
SELECT pow(2, 3);
+---------+
|pow(2, 3)|
+---------+
|      8.0|
+---------+
-- power
SELECT power(2, 3);
+-----------+
|POWER(2, 3)|
+-----------+
|        8.0|
+-----------+
-- radians
SELECT radians(180);
+-----------------+
|     RADIANS(180)|
+-----------------+
|3.141592653589793|
+-----------------+
-- rand
SELECT rand();
+------------------+
|            rand()|
+------------------+
|0.7211420708112387|
+------------------+
SELECT rand(0);
+------------------+
|           rand(0)|
+------------------+
|0.7604953758285915|
+------------------+
SELECT rand(null);
+------------------+
|        rand(NULL)|
+------------------+
|0.7604953758285915|
+------------------+
-- randn
SELECT randn();
+-------------------+
|            randn()|
+-------------------+
|-0.8175603217732732|
+-------------------+
SELECT randn(0);
+------------------+
|          randn(0)|
+------------------+
|1.6034991609278433|
+------------------+
SELECT randn(null);
+------------------+
|       randn(NULL)|
+------------------+
|1.6034991609278433|
+------------------+
-- random
SELECT random();
+-----------------+
|           rand()|
+-----------------+
|0.394205008255365|
+-----------------+
SELECT random(0);
+------------------+
|           rand(0)|
+------------------+
|0.7604953758285915|
+------------------+
SELECT random(null);
+------------------+
|        rand(NULL)|
+------------------+
|0.7604953758285915|
+------------------+
-- rint
SELECT rint(12.3456);
+-------------+
|rint(12.3456)|
+-------------+
|         12.0|
+-------------+
-- round
SELECT round(2.5, 0);
+-------------+
|round(2.5, 0)|
+-------------+
|            3|
+-------------+
-- sec
SELECT sec(0);
+------+
|SEC(0)|
+------+
|   1.0|
+------+
-- shiftleft
SELECT shiftleft(2, 1);
+---------------+
|shiftleft(2, 1)|
+---------------+
|              4|
+---------------+
-- sign
SELECT sign(40);
+--------+
|sign(40)|
+--------+
|     1.0|
+--------+
SELECT sign(INTERVAL -'100' YEAR);
+--------------------------+
|sign(INTERVAL '-100' YEAR)|
+--------------------------+
|                      -1.0|
+--------------------------+
-- signum
SELECT signum(40);
+----------+
|SIGNUM(40)|
+----------+
|       1.0|
+----------+
SELECT signum(INTERVAL -'100' YEAR);
+----------------------------+
|SIGNUM(INTERVAL '-100' YEAR)|
+----------------------------+
|                        -1.0|
+----------------------------+
-- sin
SELECT sin(0);
+------+
|SIN(0)|
+------+
|   0.0|
+------+
-- sinh
SELECT sinh(0);
+-------+
|SINH(0)|
+-------+
|    0.0|
+-------+
-- sqrt
SELECT sqrt(4);
+-------+
|SQRT(4)|
+-------+
|    2.0|
+-------+
-- tan
SELECT tan(0);
+------+
|TAN(0)|
+------+
|   0.0|
+------+
-- tanh
SELECT tanh(0);
+-------+
|TANH(0)|
+-------+
|    0.0|
+-------+
-- try_add
SELECT try_add(1, 2);
+-------------+
|try_add(1, 2)|
+-------------+
|            3|
+-------------+
SELECT try_add(2147483647, 1);
+----------------------+
|try_add(2147483647, 1)|
+----------------------+
|                  NULL|
+----------------------+
SELECT try_add(date'2021-01-01', 1);
+-----------------------------+
|try_add(DATE '2021-01-01', 1)|
+-----------------------------+
|                   2021-01-02|
+-----------------------------+
SELECT try_add(date'2021-01-01', interval 1 year);
+---------------------------------------------+
|try_add(DATE '2021-01-01', INTERVAL '1' YEAR)|
+---------------------------------------------+
|                                   2022-01-01|
+---------------------------------------------+
SELECT try_add(timestamp'2021-01-01 00:00:00', interval 1 day);
+----------------------------------------------------------+
|try_add(TIMESTAMP '2021-01-01 00:00:00', INTERVAL '1' DAY)|
+----------------------------------------------------------+
|                                       2021-01-02 00:00:00|
+----------------------------------------------------------+
SELECT try_add(interval 1 year, interval 2 year);
+---------------------------------------------+
|try_add(INTERVAL '1' YEAR, INTERVAL '2' YEAR)|
+---------------------------------------------+
|                            INTERVAL '3' YEAR|
+---------------------------------------------+
-- try_divide
SELECT try_divide(3, 2);
+----------------+
|try_divide(3, 2)|
+----------------+
|             1.5|
+----------------+
SELECT try_divide(2L, 2L);
+----------------+
|try_divide(2, 2)|
+----------------+
|             1.0|
+----------------+
SELECT try_divide(1, 0);
+----------------+
|try_divide(1, 0)|
+----------------+
|            NULL|
+----------------+
SELECT try_divide(interval 2 month, 2);
+---------------------------------+
|try_divide(INTERVAL '2' MONTH, 2)|
+---------------------------------+
|             INTERVAL '0-1' YE...|
+---------------------------------+
SELECT try_divide(interval 2 month, 0);
+---------------------------------+
|try_divide(INTERVAL '2' MONTH, 0)|
+---------------------------------+
|                             NULL|
+---------------------------------+
-- try_multiply
SELECT try_multiply(2, 3);
+------------------+
|try_multiply(2, 3)|
+------------------+
|                 6|
+------------------+
SELECT try_multiply(-2147483648, 10);
+-----------------------------+
|try_multiply(-2147483648, 10)|
+-----------------------------+
|                         NULL|
+-----------------------------+
SELECT try_multiply(interval 2 year, 3);
+----------------------------------+
|try_multiply(INTERVAL '2' YEAR, 3)|
+----------------------------------+
|              INTERVAL '6-0' YE...|
+----------------------------------+
-- try_subtract
SELECT try_subtract(2, 1);
+------------------+
|try_subtract(2, 1)|
+------------------+
|                 1|
+------------------+
SELECT try_subtract(-2147483648, 1);
+----------------------------+
|try_subtract(-2147483648, 1)|
+----------------------------+
|                        NULL|
+----------------------------+
SELECT try_subtract(date'2021-01-02', 1);
+----------------------------------+
|try_subtract(DATE '2021-01-02', 1)|
+----------------------------------+
|                        2021-01-01|
+----------------------------------+
SELECT try_subtract(date'2021-01-01', interval 1 year);
+--------------------------------------------------+
|try_subtract(DATE '2021-01-01', INTERVAL '1' YEAR)|
+--------------------------------------------------+
|                                        2020-01-01|
+--------------------------------------------------+
SELECT try_subtract(timestamp'2021-01-02 00:00:00', interval 1 day);
+---------------------------------------------------------------+
|try_subtract(TIMESTAMP '2021-01-02 00:00:00', INTERVAL '1' DAY)|
+---------------------------------------------------------------+
|                                            2021-01-01 00:00:00|
+---------------------------------------------------------------+
SELECT try_subtract(interval 2 year, interval 1 year);
+--------------------------------------------------+
|try_subtract(INTERVAL '2' YEAR, INTERVAL '1' YEAR)|
+--------------------------------------------------+
|                                 INTERVAL '1' YEAR|
+--------------------------------------------------+
-- unhex
SELECT decode(unhex('53514C'), 'UTF-8');
+----------------------------------------+
|decode(unhex(53514C), UTF-8)|
+----------------------------------------+
|                               SQL|
+----------------------------------------+
-- width_bucket
SELECT width_bucket(5.3, 0.2, 10.6, 5);
+-------------------------------+
|width_bucket(5.3, 0.2, 10.6, 5)|
+-------------------------------+
|                              3|
+-------------------------------+
SELECT width_bucket(-2.1, 1.3, 3.4, 3);
+-------------------------------+
|width_bucket(-2.1, 1.3, 3.4, 3)|
+-------------------------------+
|                              0|
+-------------------------------+
SELECT width_bucket(8.1, 0.0, 5.7, 4);
+------------------------------+
|width_bucket(8.1, 0.0, 5.7, 4)|
+------------------------------+
|                             5|
+------------------------------+
SELECT width_bucket(-0.9, 5.2, 0.5, 2);
+-------------------------------+
|width_bucket(-0.9, 5.2, 0.5, 2)|
+-------------------------------+
|                              3|
+-------------------------------+
SELECT width_bucket(INTERVAL '0' YEAR, INTERVAL '0' YEAR, INTERVAL '10' YEAR, 10);
+--------------------------------------------------------------------------+
|width_bucket(INTERVAL '0' YEAR, INTERVAL '0' YEAR, INTERVAL '10' YEAR, 10)|
+--------------------------------------------------------------------------+
|                                                                         1|
+--------------------------------------------------------------------------+
SELECT width_bucket(INTERVAL '1' YEAR, INTERVAL '0' YEAR, INTERVAL '10' YEAR, 10);
+--------------------------------------------------------------------------+
|width_bucket(INTERVAL '1' YEAR, INTERVAL '0' YEAR, INTERVAL '10' YEAR, 10)|
+--------------------------------------------------------------------------+
|                                                                         2|
+--------------------------------------------------------------------------+
SELECT width_bucket(INTERVAL '0' DAY, INTERVAL '0' DAY, INTERVAL '10' DAY, 10);
+-----------------------------------------------------------------------+
|width_bucket(INTERVAL '0' DAY, INTERVAL '0' DAY, INTERVAL '10' DAY, 10)|
+-----------------------------------------------------------------------+
|                                                                      1|
+-----------------------------------------------------------------------+
SELECT width_bucket(INTERVAL '1' DAY, INTERVAL '0' DAY, INTERVAL '10' DAY, 10);
+-----------------------------------------------------------------------+
|width_bucket(INTERVAL '1' DAY, INTERVAL '0' DAY, INTERVAL '10' DAY, 10)|
+-----------------------------------------------------------------------+
|                                                                      2|
+-----------------------------------------------------------------------+
```

#### 생성 함수
<a name="supported-sql-generator"></a>

**참고**  
이러한 SQL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).


****  

| 함수 | 설명 | 
| --- | --- | 
| explode(expr) | 배열 `expr`의 요소를 여러 행으로 구분하거나 `expr`의 요소를 여러 행과 열로 매핑합니다. 달리 지정하지 않는 한, 배열 요소에 기본 열 이름 `col`을 사용하거나 맵 요소에 `key` 및 `value`를 사용합니다. | 
| explode\$1outer(expr) | 배열 `expr`의 요소를 여러 행으로 구분하거나 `expr`의 요소를 여러 행과 열로 매핑합니다. 달리 지정하지 않는 한, 배열 요소에 기본 열 이름 `col`을 사용하거나 맵 요소에 `key` 및 `value`를 사용합니다. | 
| inline(expr) | 구문의 배열을 테이블로 탐색합니다. 달리 지정하지 않는 한, 기본적으로 열 이름 col1, col2 등을 사용합니다. | 
| inline\$1outer(expr) | 구문의 배열을 테이블로 탐색합니다. 달리 지정하지 않는 한, 기본적으로 열 이름 col1, col2 등을 사용합니다. | 
| posexplode(expr) | 배열 `expr`의 요소를 위치가 있는 여러 행으로 구분하거나 맵 `expr`의 요소를 위치가 있는 여러 행과 열로 구분합니다. 달리 지정하지 않는 한, 위치에 열 이름 `pos`, 배열의 요소에 `col` 또는 맵의 요소에 `key` 및 `value`를 사용합니다. | 
| posexplode\$1outer(expr) | 배열 `expr`의 요소를 위치가 있는 여러 행으로 구분하거나 맵 `expr`의 요소를 위치가 있는 여러 행과 열로 구분합니다. 달리 지정하지 않는 한, 위치에 열 이름 `pos`, 배열의 요소에 `col` 또는 맵의 요소에 `key` 및 `value`를 사용합니다. | 
| stack(n, expr1, ..., exprk) | `expr1`, ..., `exprk`를 `n` 행으로 구분합니다. 달리 지정하지 않는 한, 기본적으로 열 이름 col0, col1 등을 사용합니다. | 

**예시**

```
-- explode
SELECT explode(array(10, 20));
+---+
|col|
+---+
| 10|
| 20|
+---+

SELECT explode(collection => array(10, 20));
+---+
|col|
+---+
| 10|
| 20|
+---+

SELECT * FROM explode(collection => array(10, 20));
+---+
|col|
+---+
| 10|
| 20|
+---+

-- explode_outer
SELECT explode_outer(array(10, 20));
+---+
|col|
+---+
| 10|
| 20|
+---+

SELECT explode_outer(collection => array(10, 20));
+---+
|col|
+---+
| 10|
| 20|
+---+

SELECT * FROM explode_outer(collection => array(10, 20));
+---+
|col|
+---+
| 10|
| 20|
+---+

-- inline
SELECT inline(array(struct(1, 'a'), struct(2, 'b')));
+----+----+
|col1|col2|
+----+----+
|   1|   a|
|   2|   b|
+----+----+

-- inline_outer
SELECT inline_outer(array(struct(1, 'a'), struct(2, 'b')));
+----+----+
|col1|col2|
+----+----+
|   1|   a|
|   2|   b|
+----+----+

-- posexplode
SELECT posexplode(array(10,20));
+---+---+
|pos|col|
+---+---+
|  0| 10|
|  1| 20|
+---+---+

SELECT * FROM posexplode(array(10,20));
+---+---+
|pos|col|
+---+---+
|  0| 10|
|  1| 20|
+---+---+

-- posexplode_outer
SELECT posexplode_outer(array(10,20));
+---+---+
|pos|col|
+---+---+
|  0| 10|
|  1| 20|
+---+---+

SELECT * FROM posexplode_outer(array(10,20));
+---+---+
|pos|col|
+---+---+
|  0| 10|
|  1| 20|
+---+---+

-- stack
SELECT stack(2, 1, 2, 3);
+----+----+
|col0|col1|
+----+----+
|   1|   2|
|   3|NULL|
+----+----+
```

#### SELECT 절
<a name="supported-sql-select"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

OpenSearch SQL은 하나 이상의 테이블에서 결과 세트를 검색하는 데 사용되는 `SELECT` 문을 지원합니다. 다음 섹션에서는 전체 쿼리 구문과 쿼리의 다양한 구문에 대해 설명합니다.

**구문** 

```
select_statement 
[ { UNION | INTERSECT | EXCEPT } [ ALL | DISTINCT ] select_statement, ... ]
[ ORDER BY 
    { expression [ ASC | DESC ] [ NULLS { FIRST | LAST } ] 
    [ , ... ] 
    } 
]
[ SORT BY 
    { expression [ ASC | DESC ] [ NULLS { FIRST | LAST } ] 
    [ , ... ] 
    } 
]
[ WINDOW { named_window [ , WINDOW named_window, ... ] } ]
[ LIMIT { ALL | expression } ]
```

`select_statement`는 다음과 같이 정의됩니다.

```
SELECT [ ALL | DISTINCT ] { [ [ named_expression ] [ , ... ] ] }
FROM { from_item [ , ... ] }
[ PIVOT clause ]
[ UNPIVOT clause ]
[ LATERAL VIEW clause ] [ ... ]
[ WHERE boolean_expression ]
[ GROUP BY expression [ , ... ] ]
[ HAVING boolean_expression ]
```

 **파라미터** 
+ **모두** 

  관계에서 일치하는 모든 행을 선택하며 기본적으로 활성화됩니다.
+ **DISTINCT** 

  결과에서 중복 항목을 제거한 후 관계에서 일치하는 모든 행을 선택합니다.
+ **named\$1expression **

  이름이 할당된 표현식입니다. 일반적으로 열 표현식을 나타냅니다.

  구문: `expression [[AS] alias]` 
+ **from\$1item **

  테이블 관계

  조인 관계

  피벗 관계

  언피벗 관계

  테이블 값 함수

  인라인 테이블

  `[ LATERAL ] ( Subquery )`
+ **PIVOT** 

  `PIVOT` 절은 데이터와 관련하여 사용됩니다. 특정 열 값을 기반으로 집계된 값을 가져올 수 있습니다.
+ **UNPIVOT** 

  `UNPIVOT` 절은 열을 행으로 변환합니다. 값 집계를 제외하고 `PIVOT`의 반대입니다.
+ **LATERAL VIEW **

  `LATERAL VIEW` 절은 하나 이상의 행이 포함된 가상 테이블을 생성하는 `EXPLODE`와 같은 생성 함수와 함께 사용됩니다.

  `LATERAL VIEW`는 각 원래 출력 행에 행을 적용합니다.
+ **WHERE** 

  제공된 조건자를 기준으로 `FROM` 절의 결과를 필터링합니다.
+ **그룹화 기준 **

  행을 그룹화하는 데 사용되는 표현식을 지정합니다.

  이는 집계 함수(`MIN`, `MAX`, `COUNT`, `SUM`, `AVG` 등)와 함께 각 그룹의 그룹화 표현식 및 집계 값을 기반으로 행을 그룹화하는 데 사용됩니다.

  `FILTER` 절이 집계 함수에 연결되면 일치하는 행만 해당 함수에 전달됩니다.
+ **보유** 

  `GROUP BY`에 의해 생성된 행이 필터링되는 조건자를 지정합니다.

  `HAVING` 절은 그룹화가 수행된 후 행을 필터링하는 데 사용됩니다.

  `GROUP BY` 없이 `HAVING`를 지정하면 그룹화 표현식(글로벌 집계)이 없는 `GROUP BY`를 나타냅니다.
+ **ORDER BY **

  쿼리의 전체 결과 집합 행 순서를 지정합니다.

  출력 행은 여러 파티션에 걸쳐 정렬됩니다.

  이 파라미터는 `SORT BY` 및 `DISTRIBUTE BY`와 상호 배타적이며 함께 지정할 수 없습니다.
+ **SORT BY **

  각 파티션 내에서 행이 정렬되는 순서를 지정합니다.

  이 파라미터는 `ORDER BY`와 상호 배타적이며 함께 지정할 수 없습니다.
+ **LIMIT** 

  문 또는 하위 쿼리에서 반환할 수 있는 최대 행 수를 지정합니다.

  이 절은 주로 `ORDER BY`와 함께 결정적 결과를 생성하는 데 사용됩니다.
+ **boolean\$1expression **

  결과 유형 부울로 평가되는 표현식을 지정합니다.

  논리 연산자(`AND`, `OR`)를 사용하여 둘 이상의 표현식을 결합할 수 있습니다.
+ **expression** 

  하나 이상의 값, 연산자 및 값으로 평가되는 SQL 함수의 조합을 지정합니다.
+ **named\$1window **

  하나 이상의 소스 윈도우 사양에 대한 별칭을 지정합니다.

  소스 윈도우 사양은 쿼리의 윈도우 정의에서 참조할 수 있습니다.

#### WHERE 절
<a name="supported-sql-where"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

`WHERE` 절은 지정된 조건에 따라 쿼리 또는 하위 쿼리의 `FROM` 절 결과를 제한하는 데 사용됩니다.

**구문** 

```
WHERE boolean_expression
```

**파라미터**
+ **boolean\$1expression** 

  결과 유형 부울로 평가되는 표현식을 지정합니다.

  논리 연산자(`AND`, `OR`)를 사용하여 둘 이상의 표현식을 결합할 수 있습니다.

**예시**

```
CREATE TABLE person (id INT, name STRING, age INT);
INSERT INTO person VALUES
(100, 'John', 30),
(200, 'Mary', NULL),
(300, 'Mike', 80),
(400, 'Dan',  50);

-- Comparison operator in `WHERE` clause.
SELECT * FROM person WHERE id > 200 ORDER BY id;
+---+----+---+
| id|name|age|
+---+----+---+
|300|Mike| 80|
|400| Dan| 50|
+---+----+---+

-- Comparison and logical operators in `WHERE` clause.
SELECT * FROM person WHERE id = 200 OR id = 300 ORDER BY id;
+---+----+----+
| id|name| age|
+---+----+----+
|200|Mary|null|
|300|Mike|  80|
+---+----+----+

-- IS NULL expression in `WHERE` clause.
SELECT * FROM person WHERE id > 300 OR age IS NULL ORDER BY id;
+---+----+----+
| id|name| age|
+---+----+----+
|200|Mary|null|
|400| Dan|  50|
+---+----+----+

-- Function expression in `WHERE` clause.
SELECT * FROM person WHERE length(name) > 3 ORDER BY id;
+---+----+----+
| id|name| age|
+---+----+----+
|100|John|  30|
|200|Mary|null|
|300|Mike|  80|
+---+----+----+

-- `BETWEEN` expression in `WHERE` clause.
SELECT * FROM person WHERE id BETWEEN 200 AND 300 ORDER BY id;
+---+----+----+
| id|name| age|
+---+----+----+
|200|Mary|null|
|300|Mike|  80|
+---+----+----+

-- Scalar Subquery in `WHERE` clause.
SELECT * FROM person WHERE age > (SELECT avg(age) FROM person);
+---+----+---+
| id|name|age|
+---+----+---+
|300|Mike| 80|
+---+----+---+
 
-- Correlated Subquery in `WHERE` clause.
SELECT id FROM person
WHERE exists (SELECT id FROM person where id = 200);
+---+----+----+
|id |name|age |
+---+----+----+
|200|Mary|null|
+---+----+----+
```

#### GROUP BY 절
<a name="supported-sql-group-by"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

`GROUP BY` 절은 지정된 그룹화 표현식 세트를 기반으로 행을 그룹화하고, 하나 이상의 지정된 집계 함수를 기반으로 행 그룹에 대한 집계를 계산하는 데 사용됩니다.

또한 시스템은 `GROUPING SETS`, `CUBE`, `ROLLUP` 절을 통해 동일한 입력 레코드 세트에 대해 여러 집계를 수행합니다. 그룹화 표현식과 고급 집계는 `GROUP BY` 절에서 혼합하고 `GROUPING SETS ` 절에서 중첩할 수 있습니다. 자세한 내용은 `Mixed/Nested Grouping Analytics ` 섹션을 참조하세요.

`FILTER` 절이 집계 함수에 연결되면 일치하는 행만 해당 함수에 전달됩니다.

**구문** 

```
GROUP BY group_expression [ , group_expression [ , ... ] ] [ WITH { ROLLUP | CUBE } ]
GROUP BY { group_expression | { ROLLUP | CUBE | GROUPING SETS } (grouping_set [ , ...]) } [ , ... ]
```

집계 함수는 다음과 같이 정의됩니다.

```
aggregate_name ( [ DISTINCT ] expression [ , ... ] ) [ FILTER ( WHERE boolean_expression ) ]
```

**파라미터**
+ **group\$1expression **

  행을 그룹화할 기준을 지정합니다. 행 그룹화는 그룹화 표현식의 결과 값에 따라 수행됩니다.

  그룹화 표현식은 `GROUP BY a`와 같은 열 이름, `GROUP BY 0`과 같은 열 위치 또는 `GROUP BY a + b`와 같은 표현식일 수 있습니다.
+ **grouping\$1set **

  그룹화 세트는 괄호 안에 0개 이상의 쉼표로 구분된 표현식으로 지정됩니다. 그룹화 세트에 요소가 하나만 있는 경우 괄호를 생략할 수 있습니다.

  예를 들어 `GROUPING SETS ((a), (b))`는 `GROUPING SETS (a, b)`와 동일합니다.

  구문: `{ ( [ expression [ , ... ] ] ) | expression }` 
+ **GROUPING SETS **

  `GROUPING SETS` 뒤에 지정된 각 그룹화 세트의 행을 그룹화합니다.

  예를 들어 `GROUP BY GROUPING SETS ((warehouse), (product))`는 의미상 `GROUP BY warehouse` 및 `GROUP BY product`의 결과 조합과 동일합니다. 이 절은 UNION ALL의 축약형으로, `UNION ALL` 연산자의 각 분기가 `GROUPING SETS` 절에 지정된 각 그룹화 세트에 대한 집계를 수행합니다.

  마찬가지로 `GROUP BY GROUPING SETS ((warehouse, product), (product), ())`는 의미상 `GROUP BY warehouse, product, GROUP BY product` 및 전역 집계의 결과 조합과 동일합니다.
+ **ROLLUP** 

  단일 문에서 여러 수준의 집계를 지정합니다. 이 절은 여러 그룹화 세트를 기반으로 집계를 계산하는 데 사용됩니다. `ROLLUP`는 `GROUPING SETS`의 축약형입니다.

  예를 들어, `GROUP BY warehouse, product WITH ROLLUP or GROUP BY ROLLUP(warehouse, product)`은 `GROUP BY GROUPING SETS((warehouse, product), (warehouse), ())`과 같습니다.

  `GROUP BY ROLLUP(warehouse, product, (warehouse, location))`은 `GROUP BY GROUPING SETS((warehouse, product, location), (warehouse, product), (warehouse), ())`와 동일합니다.

  ROLLUP 사양의 N 요소는 N\$11 GROUPING SETS가 됩니다.
+ **CUBE** 

  CUBE 절은 GROUP BY 절에 지정된 그룹화 열의 조합을 기반으로 집계를 수행하는 데 사용됩니다. CUBE는 GROUPING SETS의 축약형입니다.

  예를 들어, `GROUP BY warehouse, product WITH CUBE or GROUP BY CUBE(warehouse, product)`은 `GROUP BY GROUPING SETS((warehouse, product), (warehouse), (product), ())`과 같습니다.

  `GROUP BY CUBE(warehouse, product, (warehouse, location))`은 `GROUP BY GROUPING SETS((warehouse, product, location), (warehouse, product), (warehouse, location), (product, warehouse, location), (warehouse), (product), (warehouse, product), ())`와 동일합니다. `CUBE` 사양의 N 요소는 2^N `GROUPING SETS`가 됩니다.
+ **혼합/중첩 그룹화 분석 **

  `GROUP BY` 절에는 여러 group\$1expressions 및 여러 `CUBE|ROLLUP|GROUPING SETS`가 포함될 수 있습니다. `GROUPING SETS`에는 `GROUPING SETS(ROLLUP(warehouse, location)`, `CUBE(warehouse, location))`, `GROUPING SETS(warehouse, GROUPING SETS(location, GROUPING SETS(ROLLUP(warehouse, location),` `CUBE(warehouse, location))))`와 같은 중첩된 `CUBE|ROLLUP|GROUPING SETS` 절도 있을 수 있습니다.

  `CUBE|ROLLUP`는 `GROUPING SETS`의 간결한 구문일 뿐입니다. `CUBE|ROLLUP`을 `GROUPING SETS`로 변환하는 방법은 위의 섹션을 참조하세요. `group_expression`은 이 컨텍스트에서 단일 그룹 `GROUPING SETS`로 취급될 수 있습니다.

  `GROUP BY` 절의 여러 `GROUPING SETS`에 대해 원래 `GROUPING SETS`의 교차 곱을 수행하여 단일 `GROUPING SETS`을 생성합니다. `GROUPING SETS` 절에서 중첩된 `GROUPING SETS`의 경우 그룹화 세트를 가져와 제거합니다.

  예를 들어, `GROUP BY warehouse, GROUPING SETS((product), ()), GROUPING SETS((location, size), (location), (size), ()) and GROUP BY warehouse, ROLLUP(product), CUBE(location, size)`은 `GROUP BY GROUPING SETS( (warehouse, product, location, size), (warehouse, product, location), (warehouse, product, size), (warehouse, product), (warehouse, location, size), (warehouse, location), (warehouse, size), (warehouse))`과 같습니다.

  `GROUP BY GROUPING SETS(GROUPING SETS(warehouse), GROUPING SETS((warehouse, product)))`은 `GROUP BY GROUPING SETS((warehouse), (warehouse, product))`와 동일합니다.
+ **aggregate\$1name **

  집계 함수 이름(`MIN`, `MAX`, `COUNT`, `SUM`, `AVG` 등)을 지정합니다.
+ **DISTINCT** 

  집계 함수로 전달되기 전에 입력 행의 중복을 제거합니다.
+ **필터** 

  `WHERE` 절의 `boolean_expression`이 true로 평가되는 입력 행을 필터링하여 집계 함수로 전달하고 다른 행은 삭제됩니다.

**예시**

```
CREATE TABLE dealer (id INT, city STRING, car_model STRING, quantity INT);
INSERT INTO dealer VALUES
(100, 'Fremont', 'Honda Civic', 10),
(100, 'Fremont', 'Honda Accord', 15),
(100, 'Fremont', 'Honda CRV', 7),
(200, 'Dublin', 'Honda Civic', 20),
(200, 'Dublin', 'Honda Accord', 10),
(200, 'Dublin', 'Honda CRV', 3),
(300, 'San Jose', 'Honda Civic', 5),
(300, 'San Jose', 'Honda Accord', 8);

-- Sum of quantity per dealership. Group by `id`.
SELECT id, sum(quantity) FROM dealer GROUP BY id ORDER BY id;
+---+-------------+
| id|sum(quantity)|
+---+-------------+
|100|           32|
|200|           33|
|300|           13|
+---+-------------+

-- Use column position in GROUP by clause.
SELECT id, sum(quantity) FROM dealer GROUP BY 1 ORDER BY 1;
+---+-------------+
| id|sum(quantity)|
+---+-------------+
|100|           32|
|200|           33|
|300|           13|
+---+-------------+

-- Multiple aggregations.
-- 1. Sum of quantity per dealership.
-- 2. Max quantity per dealership.
SELECT id, sum(quantity) AS sum, max(quantity) AS max FROM dealer GROUP BY id ORDER BY id;
+---+---+---+
| id|sum|max|
+---+---+---+
|100| 32| 15|
|200| 33| 20|
|300| 13|  8|
+---+---+---+

-- Count the number of distinct dealer cities per car_model.
SELECT car_model, count(DISTINCT city) AS count FROM dealer GROUP BY car_model;
+------------+-----+
|   car_model|count|
+------------+-----+
| Honda Civic|    3|
|   Honda CRV|    2|
|Honda Accord|    3|
+------------+-----+

-- Sum of only 'Honda Civic' and 'Honda CRV' quantities per dealership.
SELECT id, sum(quantity) FILTER (
WHERE car_model IN ('Honda Civic', 'Honda CRV')
) AS `sum(quantity)` FROM dealer
GROUP BY id ORDER BY id;
+---+-------------+
| id|sum(quantity)|
+---+-------------+
|100|           17|
|200|           23|
|300|            5|
+---+-------------+

-- Aggregations using multiple sets of grouping columns in a single statement.
-- Following performs aggregations based on four sets of grouping columns.
-- 1. city, car_model
-- 2. city
-- 3. car_model
-- 4. Empty grouping set. Returns quantities for all city and car models.
SELECT city, car_model, sum(quantity) AS sum FROM dealer
GROUP BY GROUPING SETS ((city, car_model), (city), (car_model), ())
ORDER BY city;
+---------+------------+---+
|     city|   car_model|sum|
+---------+------------+---+
|     null|        null| 78|
|     null| HondaAccord| 33|
|     null|    HondaCRV| 10|
|     null|  HondaCivic| 35|
|   Dublin|        null| 33|
|   Dublin| HondaAccord| 10|
|   Dublin|    HondaCRV|  3|
|   Dublin|  HondaCivic| 20|
|  Fremont|        null| 32|
|  Fremont| HondaAccord| 15|
|  Fremont|    HondaCRV|  7|
|  Fremont|  HondaCivic| 10|
| San Jose|        null| 13|
| San Jose| HondaAccord|  8|
| San Jose|  HondaCivic|  5|
+---------+------------+---+

-- Group by processing with `ROLLUP` clause.
-- Equivalent GROUP BY GROUPING SETS ((city, car_model), (city), ())
SELECT city, car_model, sum(quantity) AS sum FROM dealer
GROUP BY city, car_model WITH ROLLUP
ORDER BY city, car_model;
+---------+------------+---+
|     city|   car_model|sum|
+---------+------------+---+
|     null|        null| 78|
|   Dublin|        null| 33|
|   Dublin| HondaAccord| 10|
|   Dublin|    HondaCRV|  3|
|   Dublin|  HondaCivic| 20|
|  Fremont|        null| 32|
|  Fremont| HondaAccord| 15|
|  Fremont|    HondaCRV|  7|
|  Fremont|  HondaCivic| 10|
| San Jose|        null| 13|
| San Jose| HondaAccord|  8|
| San Jose|  HondaCivic|  5|
+---------+------------+---+

-- Group by processing with `CUBE` clause.
-- Equivalent GROUP BY GROUPING SETS ((city, car_model), (city), (car_model), ())
SELECT city, car_model, sum(quantity) AS sum FROM dealer
GROUP BY city, car_model WITH CUBE
ORDER BY city, car_model;
+---------+------------+---+
|     city|   car_model|sum|
+---------+------------+---+
|     null|        null| 78|
|     null| HondaAccord| 33|
|     null|    HondaCRV| 10|
|     null|  HondaCivic| 35|
|   Dublin|        null| 33|
|   Dublin| HondaAccord| 10|
|   Dublin|    HondaCRV|  3|
|   Dublin|  HondaCivic| 20|
|  Fremont|        null| 32|
|  Fremont| HondaAccord| 15|
|  Fremont|    HondaCRV|  7|
|  Fremont|  HondaCivic| 10|
| San Jose|        null| 13|
| San Jose| HondaAccord|  8|
| San Jose|  HondaCivic|  5|
+---------+------------+---+

--Prepare data for ignore nulls example
CREATE TABLE person (id INT, name STRING, age INT);
INSERT INTO person VALUES
(100, 'Mary', NULL),
(200, 'John', 30),
(300, 'Mike', 80),
(400, 'Dan', 50);

--Select the first row in column age
SELECT FIRST(age) FROM person;
+--------------------+
| first(age, false)  |
+--------------------+
| NULL               |
+--------------------+

--Get the first row in column `age` ignore nulls,last row in column `id` and sum of column `id`.
SELECT FIRST(age IGNORE NULLS), LAST(id), SUM(id) FROM person;
+-------------------+------------------+----------+
| first(age, true)  | last(id, false)  | sum(id)  |
+-------------------+------------------+----------+
| 30                | 400              | 1000     |
+-------------------+------------------+----------+
```

#### HAVING 절
<a name="supported-sql-having"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

`HAVING` 절은 지정된 조건을 기반으로 `GROUP BY`에 의해 생성된 결과를 필터링하는 데 사용됩니다. `GROUP BY` 절과 함께 사용되는 경우가 많습니다.

**구문** 

```
HAVING boolean_expression
```

**파라미터**
+ **boolean\$1expression **

  결과 유형 부울로 평가되는 표현식을 지정합니다. 논리 연산자(`AND`, `OR`)를 사용하여 둘 이상의 표현식을 결합할 수 있습니다.

  **참고** `HAVING` 절에서 지정된 표현식은 다음 항목만 참조할 수 있습니다.

  1. 상수 

  1. `GROUP BY`에 표시되는 표현식 

  1. 집계 함수 

**예시**

```
CREATE TABLE dealer (id INT, city STRING, car_model STRING, quantity INT);
INSERT INTO dealer VALUES
(100, 'Fremont', 'Honda Civic', 10),
(100, 'Fremont', 'Honda Accord', 15),
(100, 'Fremont', 'Honda CRV', 7),
(200, 'Dublin', 'Honda Civic', 20),
(200, 'Dublin', 'Honda Accord', 10),
(200, 'Dublin', 'Honda CRV', 3),
(300, 'San Jose', 'Honda Civic', 5),
(300, 'San Jose', 'Honda Accord', 8);

-- `HAVING` clause referring to column in `GROUP BY`.
SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city HAVING city = 'Fremont';
+-------+---+
|   city|sum|
+-------+---+
|Fremont| 32|
+-------+---+

-- `HAVING` clause referring to aggregate function.
SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city HAVING sum(quantity) > 15;
+-------+---+
|   city|sum|
+-------+---+
| Dublin| 33|
|Fremont| 32|
+-------+---+

-- `HAVING` clause referring to aggregate function by its alias.
SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city HAVING sum > 15;
+-------+---+
|   city|sum|
+-------+---+
| Dublin| 33|
|Fremont| 32|
+-------+---+

-- `HAVING` clause referring to a different aggregate function than what is present in
-- `SELECT` list.
SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city HAVING max(quantity) > 15;
+------+---+
|  city|sum|
+------+---+
|Dublin| 33|
+------+---+

-- `HAVING` clause referring to constant expression.
SELECT city, sum(quantity) AS sum FROM dealer GROUP BY city HAVING 1 > 0 ORDER BY city;
+--------+---+
|    city|sum|
+--------+---+
|  Dublin| 33|
| Fremont| 32|
|San Jose| 13|
+--------+---+

-- `HAVING` clause without a `GROUP BY` clause.
SELECT sum(quantity) AS sum FROM dealer HAVING sum(quantity) > 10;
+---+
|sum|
+---+
| 78|
+---+
```

#### ORDER BY 절
<a name="supported-sql-order-by"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

`ORDER BY` 절은 사용자 지정 순서로 정렬된 결과 행을 반환하는 데 사용됩니다. SORT BY 절과 달리 이 절은 출력의 전체 순서를 보장합니다.

**구문** 

```
ORDER BY { expression [ sort_direction | nulls_sort_order ] [ , ... ] }
```

**파라미터**
+ **ORDER BY **

  행을 정렬하는 데 사용되는 선택적 파라미터 `sort_direction` 및 `nulls_sort_order`와 함께 쉼표로 구분된 표현식 목록을 지정합니다.
+ **sort\$1direction **

  선택적으로, 행을 오름차순 또는 내림차순으로 정렬할지 여부를 지정합니다.

  정렬 방향의 유효한 값은 오름차순을 의미하는 `ASC`와 내림차순을 의미하는 `DESC`입니다.

  정렬 방향이 명시적으로 지정되지 않으면 기본적으로 행이 오름차순으로 정렬됩니다.

  구문: `[ ASC | DESC ] `
+ **nulls\$1sort\$1order **

  선택적으로 NULL이 아닌 값 이전/이후에 `NULL` 값을 반환할지 여부를 지정합니다.

  null\$1sort\$1order를 지정하지 않으면 정렬 순서가 `ASC`인 경우 `NULLs`를 먼저 정렬하고 정렬 순서가 `DESC`인 경우 NULLS를 마지막으로 정렬합니다.

  1. `NULLS FIRST`를 지정하면 정렬 순서에 관계없이 NULL 값이 먼저 반환됩니다.

  2. `NULLS LAST`를 지정하면 정렬 순서에 관계없이 NULL 값이 마지막으로 반환됩니다.

  구문: `[ NULLS { FIRST | LAST } ]` 

**예시**

```
CREATE TABLE person (id INT, name STRING, age INT);
INSERT INTO person VALUES
(100, 'John', 30),
(200, 'Mary', NULL),
(300, 'Mike', 80),
(400, 'Jerry', NULL),
(500, 'Dan',  50);

-- Sort rows by age. By default rows are sorted in ascending manner with NULL FIRST.
SELECT name, age FROM person ORDER BY age;
+-----+----+
| name| age|
+-----+----+
|Jerry|null|
| Mary|null|
| John|  30|
|  Dan|  50|
| Mike|  80|
+-----+----+

-- Sort rows in ascending manner keeping null values to be last.
SELECT name, age FROM person ORDER BY age NULLS LAST;
+-----+----+
| name| age|
+-----+----+
| John|  30|
|  Dan|  50|
| Mike|  80|
| Mary|null|
|Jerry|null|
+-----+----+

-- Sort rows by age in descending manner, which defaults to NULL LAST.
SELECT name, age FROM person ORDER BY age DESC;
+-----+----+
| name| age|
+-----+----+
| Mike|  80|
|  Dan|  50|
| John|  30|
|Jerry|null|
| Mary|null|
+-----+----+

-- Sort rows in ascending manner keeping null values to be first.
SELECT name, age FROM person ORDER BY age DESC NULLS FIRST;
+-----+----+
| name| age|
+-----+----+
|Jerry|null|
| Mary|null|
| Mike|  80|
|  Dan|  50|
| John|  30|
+-----+----+

-- Sort rows based on more than one column with each column having different
-- sort direction.
SELECT * FROM person ORDER BY name ASC, age DESC;
+---+-----+----+
| id| name| age|
+---+-----+----+
|500|  Dan|  50|
|400|Jerry|null|
|100| John|  30|
|200| Mary|null|
|300| Mike|  80|
+---+-----+----+
```

#### JOIN 절
<a name="supported-sql-join"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

SQL 조인은 조인 기준에 따라 두 관계의 행을 결합하는 데 사용됩니다. 다음 섹션에서는 예와 함께 전체 조인 구문과 다양한 유형의 조인에 대해 설명합니다.

**구문** 

```
relation INNER JOIN relation [ join_criteria ]
```

**파라미터**
+ **relation **

  조인할 관계를 지정합니다.
+ **join\$1type **

  조인 유형을 지정합니다.

  구문: `INNER | CROSS | LEFT OUTER`
+ **join\$1criteria **

  한 관계의 행을 다른 관계의 행과 결합하는 방법을 지정합니다.

  구문: `ON boolean_expression | USING ( column_name [ , ... ] ) `
+ **boolean\$1expression **

  반환 유형이 부울인 표현식을 지정합니다.

**조인 유형**
+ **Inner Join**

  내부 조인을 명시적으로 지정해야 합니다. 두 관계에서 일치하는 값이 있는 행을 선택합니다.

  구문: `relation INNER JOIN relation [ join_criteria ] `
+ **Left Join **

  왼쪽 조인은 왼쪽 관계의 모든 값과 오른쪽 관계의 일치하는 값을 반환하거나, 일치하는 값이 없는 경우 NULL을 추가합니다. 이를 왼쪽 외부 조인이라고도 합니다.

  구문: `relation LEFT OUTER JOIN relation [ join_criteria ]` 
+ **Cross Join **

  교차 조인은 두 관계의 카테시안 곱을 반환합니다.

  구문: `relation CROSS JOIN relation [ join_criteria ]` 

**예시**

```
-- Use employee and department tables to demonstrate different type of joins.
SELECT * FROM employee;
+---+-----+------+
| id| name|deptno|
+---+-----+------+
|105|Chloe|     5|
|103| Paul|     3|
|101| John|     1|
|102| Lisa|     2|
|104| Evan|     4|
|106|  Amy|     6|
+---+-----+------+
SELECT * FROM department;
+------+-----------+
|deptno|   deptname|
+------+-----------+
|     3|Engineering|
|     2|      Sales|
|     1|  Marketing|
+------+-----------+

-- Use employee and department tables to demonstrate inner join.
SELECT id, name, employee.deptno, deptname
FROM employee INNER JOIN department ON employee.deptno = department.deptno;
+---+-----+------+-----------|
| id| name|deptno|   deptname|
+---+-----+------+-----------|
|103| Paul|     3|Engineering|
|101| John|     1|  Marketing|
|102| Lisa|     2|      Sales|
+---+-----+------+-----------|

-- Use employee and department tables to demonstrate left join.
SELECT id, name, employee.deptno, deptname
FROM employee LEFT JOIN department ON employee.deptno = department.deptno;
+---+-----+------+-----------|
| id| name|deptno|   deptname|
+---+-----+------+-----------|
|105|Chloe|     5|       NULL|
|103| Paul|     3|Engineering|
|101| John|     1|  Marketing|
|102| Lisa|     2|      Sales|
|104| Evan|     4|       NULL|
|106|  Amy|     6|       NULL|
+---+-----+------+-----------|

-- Use employee and department tables to demonstrate cross join.
SELECT id, name, employee.deptno, deptname FROM employee CROSS JOIN department;
+---+-----+------+-----------|
| id| name|deptno|   deptname|
+---+-----+------+-----------|
|105|Chloe|     5|Engineering|
|105|Chloe|     5|  Marketing|
|105|Chloe|     5|      Sales|
|103| Paul|     3|Engineering|
|103| Paul|     3|  Marketing|
|103| Paul|     3|      Sales|
|101| John|     1|Engineering|
|101| John|     1|  Marketing|
|101| John|     1|      Sales|
|102| Lisa|     2|Engineering|
|102| Lisa|     2|  Marketing|
|102| Lisa|     2|      Sales|
|104| Evan|     4|Engineering|
|104| Evan|     4|  Marketing|
|104| Evan|     4|      Sales|
|106|  Amy|     4|Engineering|
|106|  Amy|     4|  Marketing|
|106|  Amy|     4|      Sales|
+---+-----+------+-----------|
```

#### LIMIT 절
<a name="supported-sql-limit"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

`LIMIT` 절은 `SELECT` 문에서 반환되는 행 수를 제한하는 데 사용됩니다. 일반적으로 이 절은 결과가 결정적임을 보장하기 위해 `ORDER BY`와 함께 사용됩니다.

**구문** 

```
LIMIT { ALL | integer_expression }
```

**파라미터**
+ **모두**

  지정하면 쿼리에서 모든 행이 반환됩니다. 즉, 이 옵션을 지정하면 제한이 적용되지 않습니다.
+ **integer\$1expression **

  정수를 반환하는 접을 수 있는 표현식을 지정합니다.

**예시**

```
CREATE TABLE person (name STRING, age INT);
INSERT INTO person VALUES
('Jane Doe', 25),
('Pat C', 18),
('Nikki W', 16),
('John D', 25),
('Juan L', 18),
('Jorge S', 16);

-- Select the first two rows.
SELECT name, age FROM person ORDER BY name LIMIT 2;
+-------+---+
|   name|age|
+-------+---+
|  Pat C| 18|
|Jorge S| 16|
+------+---+

-- Specifying ALL option on LIMIT returns all the rows.
SELECT name, age FROM person ORDER BY name LIMIT ALL;
+--------+---+
|    name|age|
+--------+---+
|   Pat C| 18|
| Jorge S| 16|
|  Juan L| 18|
|  John D| 25|
| Nikki W| 16|
|Jane Doe| 25|
+--------+---+

-- A function expression as an input to LIMIT.
SELECT name, age FROM person ORDER BY name LIMIT length('OPENSEARCH');
+-------+---+
|   name|age|
+-------+---+
|  Pat C| 18|
|Jorge S| 16|
| Juan L| 18|
| John D| 25|
|Nikki W| 16|
+-------+---+
```

#### CASE 절
<a name="supported-sql-case"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

`CASE` 절은 규칙을 사용하여 다른 프로그래밍 언어의 if/else 문과 마찬가지로 지정된 조건에 따라 특정 결과를 반환합니다.

**구문** 

```
CASE [ expression ] { WHEN boolean_expression THEN then_expression } [ ... ]
[ ELSE else_expression ]
END
```

**파라미터**
+ **boolean\$1expression **

  결과 유형 부울로 평가되는 표현식을 지정합니다.

  논리 연산자(`AND`, `OR`)를 사용하여 둘 이상의 표현식을 결합할 수 있습니다.
+ **then\$1expression **

  boolean\$1expression 조건에 따라 then 표현식을 지정합니다.

  `then_expression`과 `else_expression`은 모두 동일한 유형이거나 공통 유형으로 강제 변환될 수 있어야 합니다.
+ **else\$1expression **

  기본 표현식을 지정합니다.

  `then_expression`과 ` else_expression`은 모두 동일한 유형이거나 공통 유형으로 강제 변환될 수 있어야 합니다.

**예시**

```
CREATE TABLE person (id INT, name STRING, age INT);
INSERT INTO person VALUES
(100, 'John', 30),
(200, 'Mary', NULL),
(300, 'Mike', 80),
(400, 'Dan', 50);
SELECT id, CASE WHEN id > 200 THEN 'bigger' ELSE 'small' END FROM person;
+------+--------------------------------------------------+
|  id  | CASE WHEN (id > 200) THEN bigger ELSE small END  |
+------+--------------------------------------------------+
| 100  | small                                            |
| 200  | small                                            |
| 300  | bigger                                           |
| 400  | bigger                                           |
+------+--------------------------------------------------+
SELECT id, CASE id WHEN 100 then 'bigger' WHEN  id > 300 THEN '300' ELSE 'small' END FROM person;
+------+-----------------------------------------------------------------------------------------------+
|  id  | CASE WHEN (id = 100) THEN bigger WHEN (id = CAST((id > 300) AS INT)) THEN 300 ELSE small END  |
+------+-----------------------------------------------------------------------------------------------+
| 100  | bigger                                                                                        |
| 200  | small                                                                                         |
| 300  | small                                                                                         |
| 400  | small                                                                                         |
+------+-----------------------------------------------------------------------------------------------+
```

#### 공통 테이블 표현식
<a name="supported-sql-cte"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

공통 테이블 표현식(CTE)은 사용자가 SQL 문의 범위 내에서 여러 번 참조할 수 있는 임시 결과 세트를 정의합니다. CTE는 주로 `SELECT` 문에 사용됩니다.

**구문** 

```
WITH common_table_expression [ , ... ]
```

`common_table_expression`는 다음과 같이 정의됩니다.

```
Syntexpression_name [ ( column_name [ , ... ] ) ] [ AS ] ( query )
```

**파라미터** 
+ **expression\$1name **

  공통 테이블 표현식의 이름을 지정합니다.
+ **query** 

  `SELECT` 문입니다.

**예시**

```
-- CTE with multiple column aliases
WITH t(x, y) AS (SELECT 1, 2)
SELECT * FROM t WHERE x = 1 AND y = 2;
+---+---+
|  x|  y|
+---+---+
|  1|  2|
+---+---+

-- CTE in CTE definition
WITH t AS (
WITH t2 AS (SELECT 1)
SELECT * FROM t2
)
SELECT * FROM t;
+---+
|  1|
+---+
|  1|
+---+

-- CTE in subquery
SELECT max(c) FROM (
WITH t(c) AS (SELECT 1)
SELECT * FROM t
);
+------+
|max(c)|
+------+
|     1|
+------+

-- CTE in subquery expression
SELECT (
WITH t AS (SELECT 1)
SELECT * FROM t
);
+----------------+
|scalarsubquery()|
+----------------+
|               1|
+----------------+

-- CTE in CREATE VIEW statement
CREATE VIEW v AS
WITH t(a, b, c, d) AS (SELECT 1, 2, 3, 4)
SELECT * FROM t;
SELECT * FROM v;
+---+---+---+---+
|  a|  b|  c|  d|
+---+---+---+---+
|  1|  2|  3|  4|
+---+---+---+---+
```

#### EXPLAIN
<a name="supported-sql-explain"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

`EXPLAIN` 문은 입력 문에 대한 논리적/물리적 계획을 제공하는 데 사용됩니다. 기본적으로 이 절은 물리적 계획에 대한 정보만 제공합니다.

**구문** 

```
EXPLAIN [ EXTENDED | CODEGEN | COST | FORMATTED ] statement
```

**파라미터**
+ **EXTENDED** 

  구문 분석된 논리적 계획, 분석된 논리적 계획, 최적화된 논리적 계획 및 물리적 계획을 생성합니다.

  구문 분석된 논리적 계획은 쿼리에서 추출된 해결되지 않은 계획입니다.

  분석된 논리적 계획은 `unresolvedAttribute`와 `unresolvedRelation`을 완전한 형식의 객체로 변환합니다.

  최적화된 논리적 계획은 일련의 최적화 규칙을 통해 변환되므로 물리적 계획이 생성됩니다.
+ **CODEGEN** 

  물리적 계획이 있는 경우 문에 대한 코드를 생성합니다.
+ **COST** 

  계획 노드 통계를 사용할 수 있는 경우, 논리적 계획과 통계를 생성합니다.
+ **FORMATTED** 

  물리적 계획 개요와 노드 세부 정보라는 두 섹션을 생성합니다.
+ **설명** 

  설명할 SQL 문을 지정합니다.

**예시**

```
-- Default Output
EXPLAIN select k, sum(v) from values (1, 2), (1, 3) t(k, v) group by k;
+----------------------------------------------------+
|                                                plan|
+----------------------------------------------------+
| == Physical Plan ==
*(2) HashAggregate(keys=[k#33], functions=[sum(cast(v#34 as bigint))])
+- Exchange hashpartitioning(k#33, 200), true, [id=#59]
+- *(1) HashAggregate(keys=[k#33], functions=[partial_sum(cast(v#34 as bigint))])
+- *(1) LocalTableScan [k#33, v#34]
|
+----------------------------------------------------

-- Using Extended
EXPLAIN EXTENDED select k, sum(v) from values (1, 2), (1, 3) t(k, v) group by k;
+----------------------------------------------------+
|                                                plan|
+----------------------------------------------------+
| == Parsed Logical Plan ==
'Aggregate ['k], ['k, unresolvedalias('sum('v), None)]
 +- 'SubqueryAlias `t`
+- 'UnresolvedInlineTable [k, v], [List(1, 2), List(1, 3)]
   
 == Analyzed Logical Plan ==
 k: int, sum(v): bigint
 Aggregate [k#47], [k#47, sum(cast(v#48 as bigint)) AS sum(v)#50L]
 +- SubqueryAlias `t`
    +- LocalRelation [k#47, v#48]
   
 == Optimized Logical Plan ==
 Aggregate [k#47], [k#47, sum(cast(v#48 as bigint)) AS sum(v)#50L]
 +- LocalRelation [k#47, v#48]
   
 == Physical Plan ==
 *(2) HashAggregate(keys=[k#47], functions=[sum(cast(v#48 as bigint))], output=[k#47, sum(v)#50L])
+- Exchange hashpartitioning(k#47, 200), true, [id=#79]
   +- *(1) HashAggregate(keys=[k#47], functions=[partial_sum(cast(v#48 as bigint))], output=[k#47, sum#52L])
    +- *(1) LocalTableScan [k#47, v#48]
|
+----------------------------------------------------+

-- Using Formatted
EXPLAIN FORMATTED select k, sum(v) from values (1, 2), (1, 3) t(k, v) group by k;
+----------------------------------------------------+
|                                                plan|
+----------------------------------------------------+
| == Physical Plan ==
 * HashAggregate (4)
 +- Exchange (3)
    +- * HashAggregate (2)
       +- * LocalTableScan (1)
   
   
 (1) LocalTableScan [codegen id : 1]
 Output: [k#19, v#20]
        
 (2) HashAggregate [codegen id : 1]
 Input: [k#19, v#20]
        
 (3) Exchange
 Input: [k#19, sum#24L]
        
 (4) HashAggregate [codegen id : 2]
 Input: [k#19, sum#24L]
|
+----------------------------------------------------+
```

#### LATERAL SUBQUERY 절
<a name="supported-sql-lateral-subquery"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

`LATERAL SUBQUERY`는 키워드 `LATERAL` 앞에 오는 하위 쿼리입니다. 이전 `FROM` 절의 열을 참조하는 방법을 제공합니다. `LATERAL` 키워드가 없으면 하위 쿼리는 외부 쿼리의 열만 참조할 수 있지만 `FROM` 절에서는 참조할 수 없습니다. `LATERAL SUBQUERY`는 복잡한 쿼리를 단순화하고 효율성을 높입니다.

**구문** 

```
[ LATERAL ] primary_relation [ join_relation ]
```

**파라미터**
+ **primary\$1relation **

  기본 관계를 지정합니다. 다음 중 하나가 될 수 있습니다.

  1. 테이블 관계 

  1. 별칭이 지정된 쿼리 

     구문: `( query ) [ [ AS ] alias ] `

  1. 별칭이 지정된 관계 

     `Syntax: ( relation ) [ [ AS ] alias ]` 

**예시**

```
CREATE TABLE t1 (c1 INT, c2 INT);
INSERT INTO t1 VALUES (0, 1), (1, 2);
CREATE TABLE t2 (c1 INT, c2 INT);
INSERT INTO t2 VALUES (0, 2), (0, 3);
SELECT * FROM t1,
LATERAL (SELECT * FROM t2 WHERE t1.c1 = t2.c1);
+--------+-------+--------+-------+
|  t1.c1 | t1.c2 |  t2.c1 | t2.c2 |
+-------+--------+--------+-------+
|    0   |   1   |    0   |   3   |
|    0   |   1   |    0   |   2   |
+-------+--------+--------+-------+
SELECT a, b, c FROM t1,
LATERAL (SELECT c1 + c2 AS a),
LATERAL (SELECT c1 - c2 AS b),
LATERAL (SELECT a * b AS c);
+--------+-------+--------+
|    a   |   b   |    c   |
+-------+--------+--------+
|    3   |  -1   |   -3   |
|    1   |  -1   |   -1   |
+-------+--------+--------+
```

#### LATERAL VIEW 절
<a name="supported-sql-lateral-view"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

`LATERAL VIEW` 절은 하나 이상의 행이 포함된 가상 테이블을 생성하는 `EXPLODE`와 같은 생성 함수와 함께 사용됩니다. `LATERAL VIEW`는 각 원래 출력 행에 이 행을 적용합니다.

**구문** 

```
LATERAL VIEW [ OUTER ] generator_function ( expression [ , ... ] ) [ table_alias ] AS column_alias [ , ... ]
```

**파라미터**
+ **외부**

  `OUTER`가 지정된 경우 입력 배열/맵이 비어 있거나 null인 경우 null을 반환합니다.
+ **generator\$1function **

  생성 함수(`EXPLODE`, `INLINE` 등)를 지정합니다.
+ **table\$1alias **

  선택 사항인 `generator_function`의 별칭입니다.
+ **column\$1alias**

  출력 행에 사용할 수 있는 `generator_function`의 열 별칭을 나열합니다.

  `generator_function`에 출력 열이 여러 개 있는 경우 별칭이 여러 개 있을 수 있습니다.

**예시**

```
CREATE TABLE person (id INT, name STRING, age INT, class INT, address STRING);
INSERT INTO person VALUES
(100, 'John', 30, 1, 'Street 1'),
(200, 'Mary', NULL, 1, 'Street 2'),
(300, 'Mike', 80, 3, 'Street 3'),
(400, 'Dan', 50, 4, 'Street 4');
SELECT * FROM person
LATERAL VIEW EXPLODE(ARRAY(30, 60)) tableName AS c_age
LATERAL VIEW EXPLODE(ARRAY(40, 80)) AS d_age;
+------+-------+-------+--------+-----------+--------+--------+
|  id  | name  |  age  | class  |  address  | c_age  | d_age  |
+------+-------+-------+--------+-----------+--------+--------+
| 100  | John  | 30    | 1      | Street 1  | 30     | 40     |
| 100  | John  | 30    | 1      | Street 1  | 30     | 80     |
| 100  | John  | 30    | 1      | Street 1  | 60     | 40     |
| 100  | John  | 30    | 1      | Street 1  | 60     | 80     |
| 200  | Mary  | NULL  | 1      | Street 2  | 30     | 40     |
| 200  | Mary  | NULL  | 1      | Street 2  | 30     | 80     |
| 200  | Mary  | NULL  | 1      | Street 2  | 60     | 40     |
| 200  | Mary  | NULL  | 1      | Street 2  | 60     | 80     |
| 300  | Mike  | 80    | 3      | Street 3  | 30     | 40     |
| 300  | Mike  | 80    | 3      | Street 3  | 30     | 80     |
| 300  | Mike  | 80    | 3      | Street 3  | 60     | 40     |
| 300  | Mike  | 80    | 3      | Street 3  | 60     | 80     |
| 400  | Dan   | 50    | 4      | Street 4  | 30     | 40     |
| 400  | Dan   | 50    | 4      | Street 4  | 30     | 80     |
| 400  | Dan   | 50    | 4      | Street 4  | 60     | 40     |
| 400  | Dan   | 50    | 4      | Street 4  | 60     | 80     |
+------+-------+-------+--------+-----------+--------+--------+
SELECT c_age, COUNT(1) FROM person
LATERAL VIEW EXPLODE(ARRAY(30, 60)) AS c_age
LATERAL VIEW EXPLODE(ARRAY(40, 80)) AS d_age
GROUP BY c_age;
+--------+-----------+
| c_age  | count(1)  |
+--------+-----------+
| 60     | 8         |
| 30     | 8         |
+--------+-----------+
SELECT * FROM person
LATERAL VIEW EXPLODE(ARRAY()) tableName AS c_age;
+-----+-------+------+--------+----------+--------+
| id  | name  | age  | class  | address  | c_age  |
+-----+-------+------+--------+----------+--------+
+-----+-------+------+--------+----------+--------+
SELECT * FROM person
LATERAL VIEW OUTER EXPLODE(ARRAY()) tableName AS c_age;
+------+-------+-------+--------+-----------+--------+
|  id  | name  |  age  | class  |  address  | c_age  |
+------+-------+-------+--------+-----------+--------+
| 100  | John  | 30    | 1      | Street 1  | NULL   |
| 200  | Mary  | NULL  | 1      | Street 2  | NULL   |
| 300  | Mike  | 80    | 3      | Street 3  | NULL   |
| 400  | Dan   | 50    | 4      | Street 4  | NULL   |
+------+-------+-------+--------+-----------+--------+
```

#### LIKE 조건자
<a name="supported-sql-like-predicate"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

`LIKE` 조건자는 특정 패턴을 검색하는 데 사용됩니다. 이 조건자는 `ANY`, `SOME`, `ALL` 등의 한정자가 있는 여러 패턴도 지원합니다.

**구문** 

```
[ NOT ] { LIKE search_pattern [ ESCAPE esc_char ] | [ RLIKE | REGEXP ] regex_pattern }
[ NOT ] { LIKE quantifiers ( search_pattern [ , ... ]) }
```

**파라미터**
+ **search\$1pattern **

  LIKE 절로 검색할 문자열 패턴을 지정합니다. 다음과 같은 특수 패턴 일치 문자를 포함할 수 있습니다.
  + `%`는 0개 이상의 문자에 해당합니다.
  + `_`는 정확히 1문자에 해당합니다.
+ **esc\$1char **

  이스케이프 문자를 지정합니다. 기본 이스케이프 문자는 `\`입니다.
+ **regex\$1pattern **

  `RLIKE` 또는 `REGEXP` 절로 검색할 정규식 검색 패턴을 지정합니다.
+ **quantifiers** 

  `ANY`, `SOME`, `ALL` 등의 조건자 한정자를 지정합니다.

  `ANY` 또는 `SOME`는 패턴 중 하나가 입력과 일치하는 경우 true를 반환함을 의미합니다.

  `ALL`은 모든 패턴이 입력과 일치하는 경우 true를 반환함을 의미합니다.

**예시**

```
CREATE TABLE person (id INT, name STRING, age INT);
INSERT INTO person VALUES
(100, 'John', 30),
(200, 'Mary', NULL),
(300, 'Mike', 80),
(400, 'Dan',  50),
(500, 'Evan_w', 16);
SELECT * FROM person WHERE name LIKE 'M%';
+---+----+----+
| id|name| age|
+---+----+----+
|300|Mike|  80|
|200|Mary|null|
+---+----+----+
SELECT * FROM person WHERE name LIKE 'M_ry';
+---+----+----+
| id|name| age|
+---+----+----+
|200|Mary|null|
+---+----+----+
SELECT * FROM person WHERE name NOT LIKE 'M_ry';
+---+------+---+
| id|  name|age|
+---+------+---+
|500|Evan_W| 16|
|300|  Mike| 80|
|100|  John| 30|
|400|   Dan| 50|
+---+------+---+
SELECT * FROM person WHERE name RLIKE 'M+';
+---+----+----+
| id|name| age|
+---+----+----+
|300|Mike|  80|
|200|Mary|null|
+---+----+----+
SELECT * FROM person WHERE name REGEXP 'M+';
+---+----+----+
| id|name| age|
+---+----+----+
|300|Mike|  80|
|200|Mary|null|
+---+----+----+
SELECT * FROM person WHERE name LIKE '%\_%';
+---+------+---+
| id|  name|age|
+---+------+---+
|500|Evan_W| 16|
+---+------+---+
SELECT * FROM person WHERE name LIKE '%$_%' ESCAPE '$';
+---+------+---+
| id|  name|age|
+---+------+---+
|500|Evan_W| 16|
+---+------+---+
SELECT * FROM person WHERE name LIKE ALL ('%an%', '%an');
+---+----+----+
| id|name| age|
+---+----+----+
|400| Dan|  50|
+---+----+----+
SELECT * FROM person WHERE name LIKE ANY ('%an%', '%an');
+---+------+---+
| id|  name|age|
+---+------+---+
|400|   Dan| 50|
|500|Evan_W| 16|
+---+------+---+
SELECT * FROM person WHERE name LIKE SOME ('%an%', '%an');
+---+------+---+
| id|  name|age|
+---+------+---+
|400|   Dan| 50|
|500|Evan_W| 16|
+---+------+---+
SELECT * FROM person WHERE name NOT LIKE ALL ('%an%', '%an');
+---+----+----+
| id|name| age|
+---+----+----+
|100|John|  30|
|200|Mary|null|
|300|Mike|  80|
+---+----+----+
SELECT * FROM person WHERE name NOT LIKE ANY ('%an%', '%an');
+---+------+----+
| id|  name| age|
+---+------+----+
|100|  John|  30|
|200|  Mary|null|
|300|  Mike|  80|
|500|Evan_W|  16|
+---+------+----+
SELECT * FROM person WHERE name NOT LIKE SOME ('%an%', '%an');
+---+------+----+
| id|  name| age|
+---+------+----+
|100|  John|  30|
|200|  Mary|null|
|300|  Mike|  80|
|500|Evan_W|  16|
+---+------+----+
```

#### OFFSET
<a name="supported-sql-offset"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

`OFFSET` 절은 `SELECT` 문에서 반환된 행을 반환하기 전에 건너뛸 행 수를 지정하는 데 사용됩니다. 일반적으로 이 절은 결과가 결정적임을 보장하기 위해 `ORDER BY`와 함께 사용됩니다.

**구문** 

```
OFFSET integer_expression
```

**파라미터**
+ **integer\$1expression **

  정수를 반환하는 접을 수 있는 표현식을 지정합니다.

**예시**

```
CREATE TABLE person (name STRING, age INT);
INSERT INTO person VALUES
('Jane Doe', 25),
('Pat C', 18),
('Nikki W', 16),
('Juan L', 25),
('John D', 18),
('Jorge S', 16);

-- Skip the first two rows.
SELECT name, age FROM person ORDER BY name OFFSET 2;
+-------+---+
|   name|age|
+-------+---+
| John D| 18|
| Juan L| 25|
|Nikki W| 16|
|Jane Doe| 25|
+-------+---+

-- Skip the first two rows and returns the next three rows.
SELECT name, age FROM person ORDER BY name LIMIT 3 OFFSET 2;
+-------+---+
|   name|age|
+-------+---+
| John D| 18|
| Juan L| 25|
|Nikki W| 16|
+-------+---+

-- A function expression as an input to OFFSET.
SELECT name, age FROM person ORDER BY name OFFSET length('WAGON');
+-------+---+
|   name|age|
+-------+---+
|Jane Doe| 25|
+-------+---+
```

#### PIVOT 절
<a name="supported-sql-pivot"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

`PIVOT` 절은 데이터와 관련하여 사용됩니다. 특정 열 값을 기반으로 집계된 값을 가져올 수 있으며, 이는 `SELECT` 절에 사용되는 여러 열로 전환됩니다. `PIVOT` 절은 테이블 이름 또는 하위 쿼리 뒤에 지정할 수 있습니다.

**구문** 

```
PIVOT ( { aggregate_expression [ AS aggregate_expression_alias ] } [ , ... ] FOR column_list IN ( expression_list ) ) 
```

**파라미터** 
+ **aggregate\$1expression**

  `(SUM(a)`, `COUNT(DISTINCT b)` 등의 집계 표현식을 지정합니다.
+ **aggregate\$1expression\$1alias**

  집계 표현식의 별칭을 지정합니다.
+ **column\$1list**

  `FROM` 절에 새 열로 바꿀 열을 지정하는 열이 포함되어 있습니다. 대괄호를 사용하여 `(c1, c2)`와 같이 열을 묶을 수 있습니다.
+ **expression\$1list**

  `column_list`의 값을 집계 조건으로 매칭하는 데 사용되는 새 열을 지정합니다. 열의 별칭을 추가할 수도 있습니다.

**예시**

```
CREATE TABLE person (id INT, name STRING, age INT, class INT, address STRING);
INSERT INTO person VALUES
(100, 'John', 30, 1, 'Street 1'),
(200, 'Mary', NULL, 1, 'Street 2'),
(300, 'Mike', 80, 3, 'Street 3'),
(400, 'Dan', 50, 4, 'Street 4');
SELECT * FROM person
PIVOT (
SUM(age) AS a, AVG(class) AS c
FOR name IN ('John' AS john, 'Mike' AS mike)
);
+------+-----------+---------+---------+---------+---------+
|  id  |  address  | john_a  | john_c  | mike_a  | mike_c  |
+------+-----------+---------+---------+---------+---------+
| 200  | Street 2  | NULL    | NULL    | NULL    | NULL    |
| 100  | Street 1  | 30      | 1.0     | NULL    | NULL    |
| 300  | Street 3  | NULL    | NULL    | 80      | 3.0     |
| 400  | Street 4  | NULL    | NULL    | NULL    | NULL    |
+------+-----------+---------+---------+---------+---------+
SELECT * FROM person
PIVOT (
SUM(age) AS a, AVG(class) AS c
FOR (name, age) IN (('John', 30) AS c1, ('Mike', 40) AS c2)
);
+------+-----------+-------+-------+-------+-------+
|  id  |  address  | c1_a  | c1_c  | c2_a  | c2_c  |
+------+-----------+-------+-------+-------+-------+
| 200  | Street 2  | NULL  | NULL  | NULL  | NULL  |
| 100  | Street 1  | 30    | 1.0   | NULL  | NULL  |
| 300  | Street 3  | NULL  | NULL  | NULL  | NULL  |
| 400  | Street 4  | NULL  | NULL  | NULL  | NULL  |
+------+-----------+-------+-------+-------+-------+
```

#### 집합 연산자
<a name="supported-sql-set"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

집합 연산자는 두 입력 관계를 하나의 입력 관계로 결합하는 데 사용됩니다. OpenSearch SQL은 세 가지 유형의 집합 연산자를 지원합니다.
+ `EXCEPT` 또는 `MINUS`
+ `INTERSECT` 
+ `UNION` 

입력 관계는 각 열의 수와 호환되는 데이터 형식이 동일해야 합니다.

**제외** 

`EXCEPT`와 `EXCEPT ALL`은 한 관계에서 찾을 수 있지만 다른 관계에서는 찾을 수 없는 행을 반환합니다. `EXCEPT`(또는 `EXCEPT DISTINCT`)는 고유한 행만 가져오고 `EXCEPT ALL`은 결과 행에서 중복을 제거하지 않습니다. `MINUS`는 `EXCEPT`의 별칭입니다.

**구문** 

```
 [ ( ] relation [ ) ] EXCEPT | MINUS [ ALL | DISTINCT ] [ ( ] relation [ ) ] 
```

**예시**

```
-- Use table1 and table2 tables to demonstrate set operators in this page.
SELECT * FROM table1;
+---+
|  c|
+---+
|  3|
|  1|
|  2|
|  2|
|  3|
|  4|
+---+
SELECT * FROM table2;
+---+
|  c|
+---+
|  5|
|  1|
|  2|
|  2|
+---+
SELECT c FROM table1 EXCEPT SELECT c FROM table2;
+---+
|  c|
+---+
|  3|
|  4|
+---+
SELECT c FROM table1 MINUS SELECT c FROM table2;
+---+
|  c|
+---+
|  3|
|  4|
+---+
SELECT c FROM table1 EXCEPT ALL (SELECT c FROM table2);
+---+
|  c|
+---+
|  3|
|  3|
|  4|
+---+
SELECT c FROM table1 MINUS ALL (SELECT c FROM table2);
+---+
|  c|
+---+
|  3|
|  3|
|  4|
+---+
```

**INTERSECT** 

`INTERSECT`와 `INTERSECT ALL`은 두 관계 모두에서 찾을 수 있는 행을 반환합니다. `INTERSECT`(또는 `INTERSECT DISTINCT`)는 고유한 행만 가져오고 `INTERSECT ALL`은 결과 행에서 중복을 제거하지 않습니다.

**구문** 

```
 [ ( ] relation [ ) ] INTERSECT [ ALL | DISTINCT ] [ ( ] relation [ ) ]
```

**예시**

```
(SELECT c FROM table1) INTERSECT (SELECT c FROM table2);
+---+
|  c|
+---+
|  1|
|  2|
+---+
(SELECT c FROM table1) INTERSECT DISTINCT (SELECT c FROM table2);
+---+
|  c|
+---+
|  1|
|  2|
+---+
(SELECT c FROM table1) INTERSECT ALL (SELECT c FROM table2);
+---+
|  c|
+---+
|  1|
|  2|
|  2|
+---+
```

**UNION** 

`UNION`와 `UNION ALL`은 두 관계 모두에서 찾을 수 없는 행을 반환합니다. `UNION`(또는 `UNION DISTINCT`)는 고유한 행만 가져오고 `UNION ALL`은 결과 행에서 중복을 제거하지 않습니다.

**구문** 

```
 [ ( ] relation [ ) ] UNION [ ALL | DISTINCT ] [ ( ] relation [ ) ]
```

**예시**

```
(SELECT c FROM table1) UNION (SELECT c FROM table2);
+---+
|  c|
+---+
|  1|
|  3|
|  5|
|  4|
|  2|
+---+
(SELECT c FROM table1) UNION DISTINCT (SELECT c FROM table2);
+---+
|  c|
+---+
|  1|
|  3|
|  5|
|  4|
|  2|
+---+
SELECT c FROM table1 UNION ALL (SELECT c FROM table2);
+---+
|  c|
+---+
|  3|
|  1|
|  2|
|  2|
|  3|
|  4|
|  5|
|  1|
|  2|
|  2|
+---+
```

#### SORT BY 절
<a name="supported-sql-sort-by"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

`SORT BY` 절은 각 파티션 내에서 정렬된 결과 행을 사용자 지정 순서로 반환하는 데 사용됩니다. 파티션이 두 개 이상 있는 경우 `SORT BY`는 부분적으로 정렬된 결과를 반환할 수 있습니다. 이는 출력의 총 순서를 보장하는 `ORDER BY` 절과 다릅니다.

**구문** 

```
SORT BY { expression [ sort_direction | nulls_sort_order ] [ , ... ] }
```

**파라미터**
+ **SORT BY **

  각 파티션 내의 행을 정렬하는 데 사용되는 선택적 파라미터 sort\$1direction 및 nulls\$1sort\$1order와 함께 쉼표로 구분된 표현식 목록을 지정합니다.
+ **sort\$1direction **

  선택적으로, 행을 오름차순 또는 내림차순으로 정렬할지 여부를 지정합니다.

  정렬 방향의 유효한 값은 오름차순을 의미하는 `ASC`와 내림차순을 의미하는 `DESC`입니다.

  정렬 방향이 명시적으로 지정되지 않으면 기본적으로 행이 오름차순으로 정렬됩니다.

  구문: `[ ASC | DESC ]` 
+ **nulls\$1sort\$1order **

  선택적으로 NULL이 아닌 값 이전/이후에 NULL 값을 반환할지 여부를 지정합니다.

  `null_sort_order`를 지정하지 않으면 정렬 순서가 `ASC`인 경우 NULLs를 먼저 정렬하고 정렬 순서가 `DESC`인 경우 NULLS를 마지막으로 정렬합니다.

  1. `NULLS FIRST`를 지정하면 정렬 순서에 관계없이 NULL 값이 먼저 반환됩니다.

  2. `NULLS LAST`를 지정하면 정렬 순서에 관계없이 NULL 값이 마지막으로 반환됩니다.

  구문: `[ NULLS { FIRST | LAST } ] `

**예시**

```
CREATE TABLE person (zip_code INT, name STRING, age INT);
INSERT INTO person VALUES
(94588, 'Shirley Rodriguez', 50),
(94588, 'Juan Li', 18),
(94588, 'Anil K', 27),
(94588, 'John D', NULL),
(94511, 'David K', 42),
(94511, 'Aryan B.', 18),
(94511, 'Lalit B.', NULL);
-- Sort rows by `name` within each partition in ascending manner
SELECT name, age, zip_code FROM person SORT BY name;
+------------------+----+--------+
|              name| age|zip_code|
+------------------+----+--------+
|            Anil K|  27|   94588|
|           Juan Li|  18|   94588|
|            John D|null|   94588|
| Shirley Rodriguez|  50|   94588|
|          Aryan B.|  18|   94511|
|           David K|  42|   94511|
|          Lalit B.|null|   94511|
+------------------+----+--------+
-- Sort rows within each partition using column position.
SELECT name, age, zip_code FROM person SORT BY 1;
+----------------+----+----------+
|              name| age|zip_code|
+------------------+----+--------+
|            Anil K|  27|   94588|
|           Juan Li|  18|   94588|
|            John D|null|   94588|
| Shirley Rodriguez|  50|   94588|
|          Aryan B.|  18|   94511|
|           David K|  42|   94511|
|          Lalit B.|null|   94511|
+------------------+----+--------+

-- Sort rows within partition in ascending manner keeping null values to be last.
SELECT age, name, zip_code FROM person SORT BY age NULLS LAST;
+----+------------------+--------+
| age|              name|zip_code|
+----+------------------+--------+
|  18|           Juan Li|   94588|
|  27|            Anil K|   94588|
|  50| Shirley Rodriguez|   94588|
|null|            John D|   94588|
|  18|          Aryan B.|   94511|
|  42|           David K|   94511|
|null|          Lalit B.|   94511|
+--------------+--------+--------+

-- Sort rows by age within each partition in descending manner, which defaults to NULL LAST.
SELECT age, name, zip_code FROM person SORT BY age DESC;
+----+------------------+--------+
| age|              name|zip_code|
+----+------------------+--------+
|  50|          Shirley Rodriguez|   94588|
|  27|            Anil K|   94588|
|  18|           Juan Li|   94588|
|null|            John D|   94588|
|  42|           David K|   94511|
|  18|          Aryan B.|   94511|
|null|          Lalit B.|   94511|
+----+------------------+--------+

-- Sort rows by age within each partition in descending manner keeping null values to be first.
SELECT age, name, zip_code FROM person SORT BY age DESC NULLS FIRST;
+----+------------------+--------+
| age|              name|zip_code|
+----+------------------+--------+
|null|            John D|   94588|
|  50| Shirley Rodriguez|   94588|
|  27|            Anil K|   94588|
|  18|           Juan Li|   94588|
|null|          Lalit B.|   94511|
|  42|           David K|   94511|
|  18|          Aryan B.|   94511|
+--------------+--------+--------+

-- Sort rows within each partition based on more than one column with each column having
-- different sort direction.
SELECT name, age, zip_code FROM person
SORT BY name ASC, age DESC;
+------------------+----+--------+
|              name| age|zip_code|
+------------------+----+--------+
|            Anil K|  27|   94588|
|           Juan Li|  18|   94588|
|            John D|null|   94588|
| Shirley Rodriguez|  50|   94588|
|          Aryan B.|  18|   94511|
|           David K|  42|   94511|
|          Lalit B.|null|   94511|
+------------------+----+--------+
```

#### UNPIVOT
<a name="supported-sql-unpivot"></a>

**참고**  
이 SQL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[지원되는 OpenSearch SQL 명령 및 함수](#supported-directquery-sql).

`UNPIVOT` 절은 여러 열을 `SELECT` 절에 사용되는 여러 행으로 변환합니다. `UNPIVOT` 절은 테이블 이름 또는 하위 쿼리 뒤에 지정할 수 있습니다.

**구문** 

```
UNPIVOT [ { INCLUDE | EXCLUDE } NULLS ] (
    { single_value_column_unpivot | multi_value_column_unpivot }
) [[AS] alias]

single_value_column_unpivot:
    values_column
    FOR name_column
    IN (unpivot_column [[AS] alias] [, ...])

multi_value_column_unpivot:
    (values_column [, ...])
    FOR name_column
    IN ((unpivot_column [, ...]) [[AS] alias] [, ...])
```

**파라미터**
+ **unpivot\$1column **

  언피벗하려는 열을 지정하는 `FROM` 절의 열을 포함합니다.
+ **name\$1column **

  언피벗된 열의 이름을 포함하는 열의 이름입니다.
+ **values\$1column **

  언피벗된 열의 값을 포함하는 열의 이름입니다.

**예시**

```
CREATE TABLE sales_quarterly (year INT, q1 INT, q2 INT, q3 INT, q4 INT);
INSERT INTO sales_quarterly VALUES
(2020, null, 1000, 2000, 2500),
(2021, 2250, 3200, 4200, 5900),
(2022, 4200, 3100, null, null);
-- column names are used as unpivot columns
SELECT * FROM sales_quarterly
UNPIVOT (
sales FOR quarter IN (q1, q2, q3, q4)
);
+------+---------+-------+
| year | quarter | sales |
+------+---------+-------+
| 2020 | q2      | 1000  |
| 2020 | q3      | 2000  |
| 2020 | q4      | 2500  |
| 2021 | q1      | 2250  |
| 2021 | q2      | 3200  |
| 2021 | q3      | 4200  |
| 2021 | q4      | 5900  |
| 2022 | q1      | 4200  |
| 2022 | q2      | 3100  |
+------+---------+-------+
-- NULL values are excluded by default, they can be included
-- unpivot columns can be alias
-- unpivot result can be referenced via its alias
SELECT up.* FROM sales_quarterly
UNPIVOT INCLUDE NULLS (
sales FOR quarter IN (q1 AS Q1, q2 AS Q2, q3 AS Q3, q4 AS Q4)
) AS up;
+------+---------+-------+
| year | quarter | sales |
+------+---------+-------+
| 2020 | Q1      | NULL  |
| 2020 | Q2      | 1000  |
| 2020 | Q3      | 2000  |
| 2020 | Q4      | 2500  |
| 2021 | Q1      | 2250  |
| 2021 | Q2      | 3200  |
| 2021 | Q3      | 4200  |
| 2021 | Q4      | 5900  |
| 2022 | Q1      | 4200  |
| 2022 | Q2      | 3100  |
| 2022 | Q3      | NULL  |
| 2022 | Q4      | NULL  |
+------+---------+-------+
-- multiple value columns can be unpivoted per row
SELECT * FROM sales_quarterly
UNPIVOT EXCLUDE NULLS (
(first_quarter, second_quarter)
FOR half_of_the_year IN (
(q1, q2) AS H1,
(q3, q4) AS H2
)
);
+------+------------------+---------------+----------------+
|  id  | half_of_the_year | first_quarter | second_quarter |
+------+------------------+---------------+----------------+
| 2020 | H1               | NULL          | 1000           |
| 2020 | H2               | 2000          | 2500           |
| 2021 | H1               | 2250          | 3200           |
| 2021 | H2               | 4200          | 5900           |
| 2022 | H1               | 4200          | 3100           |
+------+------------------+---------------+----------------+
```

# 지원되는 PPL 명령
<a name="supported-ppl"></a>

다음 표에는 CloudWatch Logs, Amazon S3 또는 Security Lake 쿼리용으로 OpenSearch Dashboards에서 지원되는 PPL 명령과 CloudWatch Logs Insights에서 지원되는 명령이 나와 있습니다. CloudWatch Logs Insights는 CloudWatch Logs를 쿼리할 때 OpenSearch Dashboards와 동일한 PPL 구문을 사용하며, 테이블은 둘 다 CloudWatch Logs라고 합니다.

**참고**  
OpenSearch Service 외부에서 데이터를 분석할 때 명령이 OpenSearch 인덱스와 다르게 실행될 수 있습니다.

**Topics**
+ [

## 명령
](#supported-ppl-commands)
+ [

## 함수
](#supported-ppl-functions)
+ [

## OpenSearch PPL을 사용하는 CloudWatch Logs Insights 사용자를 위한 추가 정보
](#supported-ppl-for-cloudwatch-users)

## 명령
<a name="supported-ppl-commands"></a>


| PPL 명령 | 설명 | CloudWatch Logs | Amazon S3 | Security Lake |  명령 예제 | 
| --- | --- | --- | --- | --- | --- | 
| [fields 명령](#supported-ppl-fields-command) | 프로젝션이 필요한 필드 세트를 표시합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre> fields field1, field2</pre>  | 
| [where 명령](#supported-ppl-where-command) |  지정한 조건에 따라 데이터를 필터링합니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre> where field1="success"<br />| where field2 != "i -023fe0a90929d8822"<br />| fields field3, col4, col5, col6<br />| head 1000</pre>  | 
| [stats 명령](#supported-ppl-stats-command) |  집계 및 계산을 수행합니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>stats count(),<br />      count(`field1`),<br />      min(`field1`),<br />      max(`field1`),<br />      avg(`field1`)<br />by field2<br />| head 1000</pre>  | 
| [parse 명령](#supported-ppl-parse-command) |  문자열에서 정규식(regex) 패턴을 추출하고 추출된 패턴을 표시합니다. 추출된 패턴을 사용하여 새 필드를 생성하거나 데이터를 필터링할 수 있습니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>parse `field1` ".*/(?<field2>[^/]+$)"<br />| where field2 = "requestId"<br />| fields field2, `field2`<br />| head 1000</pre>  | 
| [patterns 명령](#supported-ppl-patterns-command) |  텍스트 필드에서 로그 패턴을 추출하고 검색 결과에 결과를 추가합니다. 로그를 패턴별로 그룹화하면 분석 및 문제 해결을 위해 대량의 로그 데이터에서 통계를 더 쉽게 집계할 수 있습니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.svg) 지원되지 않음 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>patterns new_field='no_numbers' pattern='[0-9]' message<br />| fields message, no_numbers</pre>  | 
| [sort 명령](#supported-ppl-sort-command) |  필드 이름을 기준으로 표시된 결과를 정렬합니다. ** sort -*FieldName***을 사용하여 내림차순으로 정렬합니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>stats count(),<br />      count(`field1`),<br />      min(`field1`) as field1Alias,<br />      max(`field1`),<br />      avg(`field1`)<br />by field2<br />| sort -field1Alias<br />| head 1000</pre>  | 
| [eval 명령](#supported-ppl-eval-command) |  필드 값을 수정 또는 처리하고 다른 필드에 저장합니다. 이는 열을 수학적으로 수정하거나, 열에 문자열 함수를 적용하거나, 열에 날짜 함수를 적용하는 데 유용합니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>eval field2 = `field1` * 2<br />| fields field1, field2<br />| head 20</pre>  | 
| [rename 명령](#supported-ppl-rename-command) |  검색 결과에서 하나 이상의 필드 이름을 바꿉니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>rename field2 as field1<br />| fields field1</pre>  | 
| [head 명령](#supported-ppl-head-command) |  표시된 쿼리 결과를 처음 N개 행으로 제한합니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre> fields `@message`<br />| head 20</pre>  | 
| [grok 명령](#supported-ppl-grok-command) |  정규식을 기반으로 grok 패턴으로 텍스트 필드를 구문 분석하고 검색 결과에 결과를 추가합니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre> grok email '.+@%{HOSTNAME:host}'<br />| fields email</pre>  | 
| [top 명령](#supported-ppl-top-command) |  필드의 가장 빈번한 값을 찾습니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre> top 2 Field1 by Field2</pre>  | 
| [dedup 명령](#supported-ppl-dedup-command) |  지정한 필드를 기반으로 중복 항목을 제거합니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>dedup field1<br />| fields field1, field2, field3</pre>  | 
| [join 명령](#supported-ppl-join-commands) |  두 데이터 세트를 하나로 조인합니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>source=customer<br />| join ON c_custkey = o_custkey orders<br />| head 10</pre>  | 
| [lookup 명령](#supported-ppl-lookup-commands) |  조회 인덱스(차원 테이블)의 데이터를 추가하거나 대체하여 검색 데이터를 보강합니다. 인덱스의 필드를 차원 테이블의 값으로 확장하거나, 조회 조건이 일치할 때 값을 추가하거나 바꿀 수 있습니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.svg) 지원되지 않음 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>where orderType = 'Cancelled'<br />| lookup account_list, mkt_id AS mkt_code<br />  replace amount, account_name as name<br />| stats count(mkt_code), avg(amount)<br />  by name</pre>  | 
| [subquery 명령](#supported-ppl-subquery-commands) | 파이프 처리 언어(PPL) 문 내에서 복잡한 중첩 쿼리를 수행합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>where id in [<br />  subquery source=users<br />  | where user in [<br />    subquery source=actions<br />    | where action="login"<br />    | fields user<br />  ]<br />  | fields uid<br />]</pre>  | 
| [rare 명령](#supported-ppl-rare-command) |  필드 목록에 있는 모든 필드의 가장 빈도가 낮은 값을 찾습니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre> rare Field1 by Field2</pre>  | 
| [trendline 명령](#supported-ppl-trendline-commands) | 필드의 이동 평균을 계산합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre> trendline sma(2, field1) as field1Alias</pre>  | 
| [eventstats 명령](#supported-ppl-eventstats-command) | 계산된 요약 통계로 이벤트 데이터를 보강합니다. 이벤트 내에서 지정된 필드를 분석하고 다양한 통계 측정값을 계산한 다음, 이러한 결과를 각 원래 이벤트에 새 필드로 추가합니다. |  ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨(`count()` 제외)  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre> eventstats sum(field1) by field2</pre>  | 
| [flatten 명령](#supported-ppl-flatten-command) |  필드를 평면화합니다. 필드는 `struct<?,?> or array<struct<?,?>>` 유형이어야 합니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre> source=table | flatten field1</pre>  | 
| [필드 요약](#supported-ppl-field-summary-command) | 각 필드(count, distinct count, min, max, avg, stddev, mean)의 기본 통계를 계산합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨(쿼리당 필드 1개) | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>where field1 != 200<br />| fieldsummary includefields=field1 nulls=true</pre>  | 
| [fillnull 명령](#supported-ppl-fillnull-command) | 입력한 값으로 null 필드를 채웁니다. 하나 이상의 필드에 사용할 수 있습니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>fields field1<br />| eval field2=field1<br />| fillnull value=0 field1</pre>  | 
| [expand 명령](#supported-ppl-expand-command) | 지정된 필드의 각 값에 대해 새 행을 생성하여 여러 값이 포함된 필드를 별도의 행으로 분할합니다. | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>expand employee<br />| stats max(salary) as max<br />  by state, company</pre>  | 
| [describe 명령](#supported-ppl-describe-command) |  테이블, 스키마 및 카탈로그의 구조 및 메타데이터에 대한 자세한 정보를 가져옵니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.svg) 지원되지 않음 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre> describe schema.table</pre>  | 

## 함수
<a name="supported-ppl-functions"></a>


| PPL 함수 | 설명 | CloudWatch Logs | Amazon S3 | Security Lake |  명령 예제 | 
| --- | --- | --- | --- | --- | --- | 
|  [PPL 문자열 함수](#supported-ppl-string-functions) (`CONCAT`, `CONCAT_WS`, `LENGTH`, `LOWER`, `LTRIM`, `POSITION`, `REVERSE`, `RIGHT`, `RTRIM`, `SUBSTRING`, `TRIM`, `UPPER`)  |  PPL 쿼리 내에서 문자열 및 텍스트 데이터를 조작하고 변환할 수 있는 PPL의 내장 함수입니다. 변환 사례, 문자열 결합, 부분 추출, 텍스트 정리 등을 예로 들 수 있습니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>eval col1Len = LENGTH(col1)<br />| fields col1Len</pre>  | 
|  [PPL 날짜 및 시간 함수](#supported-ppl-date-time-functions) (`DAY`, `DAYOFMONTH`, `DAY_OF_MONTH`,`DAYOFWEEK`, `DAY_OF_WEEK`, `DAYOFYEAR`, `DAY_OF_YEAR`, `DAYNAME`, `FROM_UNIXTIME`, `HOUR`, `HOUR_OF_DAY`, `LAST_DAY`, `LOCALTIMESTAMP`, `LOCALTIME`, `MAKE_DATE`, `MINUTE`, `MINUTE_OF_HOUR`, `MONTH`, `MONTHNAME`, `MONTH_OF_YEAR`, `NOW`, `QUARTER`, `SECOND`, `SECOND_OF_MINUTE`, `SUBDATE`, `SYSDATE`, `TIMESTAMP`, `UNIX_TIMESTAMP`, `WEEK`, `WEEKDAY`, `WEEK_OF_YEAR`, `DATE_ADD`, `DATE_SUB`, `TIMESTAMPADD`, `TIMESTAMPDIFF`, `UTC_TIMESTAMP`, `CURRENT_TIMEZONE`)  |  PPL 쿼리에서 날짜 및 타임스탬프 데이터를 처리하고 변환하는 내장 함수입니다. 예: **date\$1add**, **date\$1format**, **datediff**, **current\$1date**.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>eval newDate = ADDDATE(DATE('2020-08-26'), 1)<br />| fields newDate</pre>  | 
|  [PPL 조건 함수](#supported-ppl-condition-functions) (`EXISTS`, `IF`, `IFNULL`, `ISNOTNULL`, `ISNULL`, `NULLIF`)  |  여러 행에서 계산을 수행하여 단일 요약 값을 생성하는 내장 함수입니다. 예: **sum**, **count**, **avg**, **max**, **min**.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>eval field2 = isnull(col1)<br />| fields field2, col1, field3  </pre>  | 
|  [PPL 수학 함수](#supported-ppl-math-functions) (`ABS`, `ACOS`, `ASIN`, `ATAN`, `ATAN2`, `CEIL`, `CEILING`, `CONV`, `COS`, `COT`, `CRC32`, `DEGREES`, `E`, `EXP`, `FLOOR`, `LN`, `LOG`, `LOG2`, `LOG10`, `MOD`, `PI`. `POW`, `POWER`, `RADIANS`, `RAND`, `ROUND`, `SIGN`, `SIN`, `SQRT`, `CBRT`)  |  PPL 쿼리에서 수학 계산 및 변환을 수행하기 위한 내장 함수입니다. 예: **abs**(절대값), **round**(숫자 반올림), **sqrt**(제곱근), **pow**(제곱 계산), **ceil**(가장 가까운 정수로 반올림).  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>eval field2 = ACOS(col1)<br />| fields col1</pre>  | 
|  [PPL 표현식](#supported-ppl-expressions) (산술 연산자(`+`, `-`, `*`), 조건자 연산자(`>. <`, `IN)`)  |  표현식, 특히 값 표현식에 대한 기본 제공 함수는 스칼라 값을 반환합니다. 표현식의 유형과 형식은 다릅니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>where age > (25 + 5)<br />| fields age  </pre>  | 
|  [PPL IP 주소 함수](#supported-ppl-ip-address-functions) (`CIDRMATCH`)  |  CIDR과 같은 IP 주소를 처리하기 위한 내장 함수입니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>where cidrmatch(ip, '***********/24')<br />| fields ip </pre>  | 
|  [PPL JSON 함수](#supported-ppl-json-functions) (`ARRAY_LENGTH`, `ARRAY_LENGTH`, `JSON`, `JSON_ARRAY`, `JSON_EXTRACT`, `JSON_KEYS`, `JSON_OBJECT`, `JSON_VALID`, `TO_JSON_STRING`)  |  배열, 추출, 검증 등, JSON을 처리하기 위한 내장 함수입니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>eval `json_extract('{"a":"b"}', '$.a')` = json_extract('{"a":"b"}', '$a')</pre>  | 
|  [PPL Lambda 함수](#supported-ppl-lambda-functions) (`EXISTS`, `FILTER`, `REDUCE`, `TRANSFORM`)  |  배열, 추출, 검증 등, JSON을 처리하기 위한 내장 함수입니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/negative_icon.svg) 지원되지 않음 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>eval array = json_array(1, -1, 2),<br />     result = filter(array, x -> x > 0)<br />| fields result</pre>  | 
|  [PPL 암호화 해시 함수](#supported-ppl-cryptographic-functions) (`MD5`, `SHA1`, `SHA2`)  |  검증, 비교 또는 더 복잡한 보안 프로토콜의 일부로 사용할 수 있는, 고유한 데이터 지문을 생성할 수 있는 내장 함수입니다.  | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 | ![\[alt text not found\]](http://docs.aws.amazon.com/ko_kr/opensearch-service/latest/developerguide/images/success_icon.svg) 지원됨 |  <pre>eval `MD5('hello')` = MD5('hello')<br />| fields `MD5('hello')`</pre>  | 

## OpenSearch PPL을 사용하는 CloudWatch Logs Insights 사용자를 위한 추가 정보
<a name="supported-ppl-for-cloudwatch-users"></a>

CloudWatch Logs Insights는 대부분의 OpenSearch PPL 명령 및 함수를 지원하지만 일부 명령 및 함수는 현재 지원되지 않습니다. 예를 들어 현재 PPL에서 조회 명령을 지원하지 않습니다. 2025년 6월 2일부터, 이제 CloudWatch Logs Insights는 PPL에서 JOIN, 하위 쿼리, Flatten, Fillnull, Expand, Cidrmatch 및 JSON 함수를 지원합니다. 지원되는 쿼리 명령 및 함수의 전체 목록은 위 표의 Amazon CloudWatch Logs 열을 참조하세요.

### 샘플 쿼리 및 할당량
<a name="sample-queries"></a>

다음은 CloudWatch 데이터를 쿼리하는 CloudWatch Logs Insights 사용자와 OpenSearch 사용자 모두에게 적용됩니다.

OpenSearch Service에서 CloudWatch Logs를 쿼리할 때 적용되는 제한에 대한 자세한 내용은 Amazon CloudWatch Logs 사용 설명서의 [CloudWatch Logs 할당량](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/cloudwatch_limits_cwl.html)을 참조하세요. 제한에는 쿼리할 수 있는 CloudWatch Log 그룹 수, 실행할 수 있는 최대 동시 쿼리 수, 최대 쿼리 실행 시간 및 결과에 반환된 최대 행 수가 포함됩니다. CloudWatch Logs를 쿼리하는 데 사용하는 언어(즉, OpenSearch PPL, SQL 및 Logs Insights QL)에 관계없이 제한은 동일합니다.

### PPL 명령
<a name="supported-ppl-commands-details"></a>

**Topics**
+ [

#### 설명
](#supported-ppl-comment)
+ [

#### 상관 관계 명령
](#supported-ppl-correlation-commands)
+ [

#### dedup 명령
](#supported-ppl-dedup-command)
+ [

#### describe 명령
](#supported-ppl-describe-command)
+ [

#### eval 명령
](#supported-ppl-eval-command)
+ [

#### eventstats 명령
](#supported-ppl-eventstats-command)
+ [

#### expand 명령
](#supported-ppl-expand-commands)
+ [

#### explain 명령
](#supported-ppl-explain-command)
+ [

#### fillnull 명령
](#supported-ppl-fillnull-command)
+ [

#### fields 명령
](#supported-ppl-fields-command)
+ [

#### flatten 명령
](#supported-ppl-flatten-command)
+ [

#### grok 명령
](#supported-ppl-grok-command)
+ [

#### head 명령
](#supported-ppl-head-command)
+ [

#### join 명령
](#supported-ppl-join-commands)
+ [

#### lookup 명령
](#supported-ppl-lookup-commands)
+ [

#### parse 명령
](#supported-ppl-parse-command)
+ [

#### patterns 명령
](#supported-ppl-patterns-command)
+ [

#### rare 명령
](#supported-ppl-rare-command)
+ [

#### rename 명령
](#supported-ppl-rename-command)
+ [

#### search 명령
](#supported-ppl-search-command)
+ [

#### sort 명령
](#supported-ppl-sort-command)
+ [

#### stats 명령
](#supported-ppl-stats-command)
+ [

#### subquery 명령
](#supported-ppl-subquery-commands)
+ [

#### top 명령
](#supported-ppl-top-command)
+ [

#### trendline 명령
](#supported-ppl-trendline-commands)
+ [

#### where 명령
](#supported-ppl-where-command)
+ [

#### 필드 요약
](#supported-ppl-field-summary-command)
+ [

#### expand 명령
](#supported-ppl-expand-command)
+ [

#### PPL 함수
](#supported-ppl-functions-details)

#### 설명
<a name="supported-ppl-comment"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

PPL은 줄 주석과 블록 주석을 모두 지원합니다. 시스템은 주석 텍스트를 평가하지 않습니다.

**줄 주석**  
줄 주석은 두 개의 슬래시(//)로 시작하고 새 줄로 끝납니다.

예제: 

```
os> source=accounts | top gender // finds most common gender of all the accounts
fetched rows / total rows = 2/2
+----------+
| gender   |
|----------|
| M        |
| F        |
+----------+
```

**블록 주석**  
블록 주석은 슬래시 뒤에 별표(\$1\$1)로 시작하고, 별표 뒤에 슬래시(\$1/)로 끝납니다.

예제:

```
os> source=accounts | dedup 2 gender /* dedup the document with gender field keep 2 duplication */ | fields account_number, gender
fetched rows / total rows = 3/3
+------------------+----------+
| account_number   | gender   |
|------------------+----------|
| 1                | M        |
| 6                | M        |
| 13               | F        |
+------------------+----------+
```

#### 상관 관계 명령
<a name="supported-ppl-correlation-commands"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

일반적인 차원과 기간에 따라 다양한 데이터 소스를 상호 연관시킬 수 있습니다.

이 상관 관계는 동일한 기간을 공유하지만 공식적으로 동기화되지 않은 다양한 수직 요소의 대량 데이터를 처리할 때 매우 중요합니다.

이러한 다양한 데이터 소스를 기간 및 유사한 차원에 따라 상호 연관시켜 데이터를 보강하고 중요한 인사이트를 도출할 수 있습니다.

**예제**  
관찰성 도메인에는 세 가지 개별 데이터 소스가 있습니다.
+ 로그
+ Metrics
+ 트레이스

이러한 데이터 소스는 공통 차원을 공유할 수 있습니다. 한 데이터 소스에서 다른 데이터 소스로 전환하려면 데이터 소스의 상관 관계를 올바르게 지정해야 합니다. 시맨틱 명명 규칙을 사용하여 로그, 트레이스 및 지표에서 공유 요소를 식별할 수 있습니다.

예제:

```
{
  "@timestamp": "2018-07-02T22:23:00.186Z",
  "aws": {
    "elb": {
      "backend": {
        "http": {
          "response": {
            "status_code": 500
          }
        },
        "ip": "********",
        "port": "80"
      },
      ...
     "target_port": [
        "10.0.0.1:80"
      ],
      "target_status_code": [
        "500"
      ],
      "traceId": "Root=1-58337262-36d228ad5d99923122bbe354",
      "type": "http"
    }
  },
  "cloud": {
    "provider": "aws"
  },
  "http": {
    "request": {
    ...
  },
  "communication": {
    "source": {
      "address": "**************",
      "ip": "**************",
      "port": 2817
    }
  },
  "traceId": "Root=1-58337262-36d228ad5d99923122bbe354"
}
```

이 예제는 AWS 에 있는 서비스에서 도착하는 ELB 로그를 보여줍니다 AWS. 오류를 나타내는, 상태 코드가 500인 백엔드 HTTP 응답을 보여 줍니다. 이로 인해 알림이 트리거되거나 정기적인 모니터링 프로세스에 추가될 수 있습니다. 다음 단계는 철저한 조사를 위해 이 이벤트와 관련된 데이터를 수집하는 것입니다.

기간과 관련된 모든 데이터를 쿼리하고 싶을 수 있지만 이 접근 방식은 너무 방대할 수 있습니다. 결국 정보가 너무 많아 근본 원인을 식별하는 것보다 관련 없는 데이터를 필터링하는 데 더 많은 시간을 소모할 수 있습니다.

대신 다른 소스의 데이터를 상호 연관시켜 보다 타겟팅된 접근 방식을 사용할 수 있습니다. 상관 관계에는 다음 차원을 사용할 수 있습니다.
+ **IP** - `"ip": "10.0.0.1" | "ip": "**************"`
+ **Port** - `"port": 2817 | "target_port": "10.0.0.1:80"`

추가 추적 및 지표 인덱스에 액세스할 수 있고 스키마 구조에 익숙하다면 보다 정확한 상관 관계 쿼리를 생성할 수 있습니다.

다음은 상호 연관시킬 수 있는 HTTP 정보가 포함된 추적 인덱스 문서의 예입니다.

```
{
  "traceId": "c1d985bd02e1dbb85b444011f19a1ecc",
  "spanId": "55a698828fe06a42",
  "traceState": [],
  "parentSpanId": "",
  "name": "mysql",
  "kind": "CLIENT",
  "@timestamp": "2021-11-13T20:20:39+00:00",
  "events": [
    {
      "@timestamp": "2021-03-25T17:21:03+00:00",
       ...
    }
  ],
  "links": [
    {
      "traceId": "c1d985bd02e1dbb85b444011f19a1ecc",
      "spanId": "55a698828fe06a42w2",
      },
      "droppedAttributesCount": 0
    }
  ],
  "resource": {
    "service@name": "database",
    "telemetry@sdk@name": "opentelemetry",
    "host@hostname": "ip-172-31-10-8.us-west-2.compute.internal"
  },
  "status": {
    ...
  },
  "attributes": {
    "http": {
      "user_agent": {
        "original": "Mozilla/5.0"
      },
      "network": {
         ...
        }
      },
      "request": {
         ...
        }
      },
      "response": {
        "status_code": "200",
        "body": {
          "size": 500
        }
      },
      "client": {
        "server": {
          "socket": {
            "address": "***********",
            "domain": "example.com",
            "port": 80
          },
          "address": "***********",
          "port": 80
        },
        "resend_count": 0,
        "url": {
          "full": "http://example.com"
        }
      },
      "server": {
        "route": "/index",
        "address": "***********",
        "port": 8080,
        "socket": {
         ...
        },
        "client": {
         ...
         }
        },
        "url": {
         ...
        }
      }
    }
  }
}
```

이 접근 방식에서는 시스템의 동작과 조건을 이해하는 데 도움이 되는 elb 로그와 상호 연관될 수 있는 `traceId`와 http의 클라이언트/서버 `ip`를 살펴볼 수 있습니다.

**새 상관 관계 쿼리 명령**  
다음은 이러한 유형의 조사를 허용하는 새로운 명령입니다.

```
source alb_logs, traces | where alb_logs.ip="10.0.0.1" AND alb_logs.cloud.provider="aws"| 
correlate exact fields(traceId, ip) scope(@timestamp, 1D) mapping(alb_logs.ip = traces.attributes.http.server.address, alb_logs.traceId = traces.traceId )
```

명령의 각 부분이 수행하는 작업은 다음과 같습니다.

1. `source alb_logs, traces` - 상호 연관시킬 데이터 소스를 선택합니다.

1. `where ip="10.0.0.1" AND cloud.provider="aws"` - 검색 범위를 좁힙니다.

1. `correlate exact fields(traceId, ip)` - 다음 필드의 정확한 일치를 기준으로 데이터를 상호 연관시키도록 시스템에 지시합니다.
   + `ip` 필드에는 명시적 필터 조건이 있으므로 모든 데이터 소스의 상관 관계에 사용됩니다.
   + `traceId` 필드에는 명시적 필터가 없으므로 모든 데이터 소스에 동일한 traceIds를 매칭합니다.

필드 이름은 상관 관계 명령 내에서 함수의 논리적 의미를 나타냅니다. 실제 조인 조건은 사용자가 제공하는 매핑 문에 따라 달라집니다.

`exact`라는 용어는 상관 관계 문이 쿼리 문을 이행하기 위해 모든 필드가 일치해야 함을 의미합니다.

`approximate`라는 용어는 모범 사례 시나리오에서 매칭을 시도하며 부분 일치가 있는 행을 거부하지 않습니다.

**다른 필드 매핑 처리**  
데이터 소스 간에 동일한 논리 필드(예: `ip`)의 이름이 다른 경우 경로 필드의 명시적 매핑을 제공해야 합니다. 이를 처리하기 위해 상관 관계 조건을 확장하여 서로 다른 필드 이름과 유사한 논리적 의미를 매칭할 수 있습니다. 이를 수행하는 방법은 다음과 같습니다.

```
alb_logs.ip = traces.attributes.http.server.address, alb_logs.traceId = traces.traceId    
```

상관 관계 조인에 참여하는 각 필드에 대해 이 상관 관계 명령으로 조인할 모든 테이블이 포함된 관련 매핑 문을 제공해야 합니다.

**예제**  
이 예에는 두 가지 소스(`alb_logs, traces`)가 있습니다.

2개의 필드(`traceId, ip`)가 있습니다.

2개의 매핑 문(`alb_logs.ip = traces.attributes.http.server.address, alb_logs.traceId = traces.traceId`)이 있습니다.

**상관 관계 기간 범위 지정**  
실행 엔진(드라이버)에서 수행하는 작업을 간소화하기 위해 범위 문을 추가할 수 있습니다. 이렇게 하면 이 검색의 범위를 지정해야 하는 시간에 대한 조인 쿼리가 명시적으로 지정됩니다.

`scope(@timestamp, 1D)` i

이 예에서는 검색 범위를 일 단위로 설정했기 때문에 같은 날에 나타나는 상관 관계가 함께 그룹화됩니다. 이 범위 지정 메커니즘은 결과를 단순화하고 더 잘 제어할 수 있도록 하여 필요에 따라 증분 검색 해상도를 지원합니다.

**드라이버 지원**  
새 상관 관계 명령은 사실 '숨겨진' 조인 명령이라고 할 수 있습니다. 따라서 다음 PPL 드라이버만 이 명령을 지원합니다. 이러한 드라이버에서 상관 관계 명령은 적절한 Catalyst Join 논리적 계획으로 직접 변환됩니다.

**예제**  
`source alb_logs, traces, metrics | where ip="10.0.0.1" AND cloud.provider="aws"| correlate exact on (ip, port) scope(@timestamp, 2018-07-02T22:23:00, 1 D)`

**논리적 계획:**

```
'Project [*]
+- 'Join Inner, ('ip && 'port)
   :- 'Filter (('ip === "10.0.0.1" & 'cloud.provider === "aws") & inTimeScope('@timestamp, "2018-07-02T22:23:00", "1 D"))
      +- 'UnresolvedRelation [alb_logs]
   +- 'Join Inner, ('ip & 'port)
      :- 'Filter (('ip === "10.0.0.1" & 'cloud.provider === "aws") & inTimeScope('@timestamp, "2018-07-02T22:23:00", "1 D"))
         +- 'UnresolvedRelation [traces]
      +- 'Filter (('ip === "10.0.0.1" & 'cloud.provider === "aws") & inTimeScope('@timestamp, "2018-07-02T22:23:00", "1 D"))
         +- 'UnresolvedRelation [metrics]
```

catalyst 엔진은 가장 효율적인 조인 순서에 따라 이 쿼리를 최적화합니다.

#### dedup 명령
<a name="supported-ppl-dedup-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`dedup` 명령을 사용하여 지정된 필드를 기반으로 검색 결과에서 동일한 문서를 제거합니다.

**구문**  
다음 구문을 사용합니다.

```
dedup [int] <field-list> [keepempty=<bool>] [consecutive=<bool>] 
```

**`int`**
+ 선택 사항.
+ `dedup` 명령은 <int>를 지정할 때 각 조합에 대해 여러 이벤트를 유지합니다. <int>의 값은 0보다 커야 합니다. 숫자를 지정하지 않으면 처음 발생한 이벤트만 유지됩니다. 다른 모든 중복 항목은 결과에서 제거됩니다.
+ 기본값: 1

**`keepempty`**
+ 선택 사항.
+ true인 경우 필드 목록의 필드에 NULL 값이 있거나 MISSING인 문서를 유지합니다.
+ 기본값: false

**`consecutive`**
+ 선택 사항.
+ true인 경우 값의 연속 중복 조합이 있는 이벤트만 제거합니다.
+ 기본값: false

**`field-list`**
+ 필수.
+ 쉼표로 구분된 필드 목록입니다. 최소 한 개 이상의 필드가 필요합니다.

**예 1: 필드 하나로 중복 제거**  
이 예에서는 성별 필드를 사용하여 문서를 중복 제거하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | dedup gender | fields account_number, gender;
fetched rows / total rows = 2/2
+------------------+----------+
| account_number   | gender   |
|------------------+----------|
| 1                | M        |
| 13               | F        |
+------------------+----------+
```

**예 2: 중복 문서 2개 유지**  
이 예에서는 성별 필드가 있는 중복된 문서 두 개를 유지하면서 중복 제거하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | dedup 2 gender | fields account_number, gender;
fetched rows / total rows = 3/3
+------------------+----------+
| account_number   | gender   |
|------------------+----------|
| 1                | M        |
| 6                | M        |
| 13               | F        |
+------------------+----------+
```

**예 3: 기본적으로 빈 필드 유지 또는 무시**  
이 예에서는 null 값 필드를 유지하여 문서를 중복 제거하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | dedup email keepempty=true | fields account_number, email;
fetched rows / total rows = 4/4
+------------------+-----------------------+
| account_number   | email                 |
+------------------+-----------------------+
| 1                | john_doe@example.com  |
| 6                | jane_doe@example.com  |
| 13               | null                  |
| 18               | juan_li@example.com   |
+------------------+-----------------------+
```

이 예에서는 빈 값 필드를 무시하여 문서를 중복 제거하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | dedup email | fields account_number, email;
fetched rows / total rows = 3/3
+------------------+-----------------------+
| account_number   | email                 |
+------------------+-----------------------+
| 1                | john_doe@example.com  |
| 6                | jane_doe@example.com  |
| 18               | juan_li@example.com   |
+------------------+-----------------------+
```

**예 4: 연속 문서 중복 제거**  
이 예에서는 연속 문서를 중복 제거하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | dedup gender consecutive=true | fields account_number, gender;
fetched rows / total rows = 3/3
+------------------+----------+
| account_number   | gender   |
+------------------+----------+
| 1                | M        |
| 13               | F        |
| 18               | M        |
+------------------+----------+
```

**추가 예제**
+ `source = table | dedup a | fields a,b,c`
+ `source = table | dedup a,b | fields a,b,c`
+ `source = table | dedup a keepempty=true | fields a,b,c`
+ `source = table | dedup a,b keepempty=true | fields a,b,c`
+ `source = table | dedup 1 a | fields a,b,c`
+ `source = table | dedup 1 a,b | fields a,b,c`
+ `source = table | dedup 1 a keepempty=true | fields a,b,c`
+ `source = table | dedup 1 a,b keepempty=true | fields a,b,c`
+ `source = table | dedup 2 a | fields a,b,c`
+ `source = table | dedup 2 a,b | fields a,b,c`
+ `source = table | dedup 2 a keepempty=true | fields a,b,c`
+ `source = table | dedup 2 a,b keepempty=true | fields a,b,c`
+ `source = table | dedup 1 a consecutive=true| fields a,b,c`(연속 중복 제거는 지원되지 않음)

**제한 사항**
+ `| dedup 2 a, b keepempty=false`의 경우

  ```
  DataFrameDropColumns('_row_number_)
  +- Filter ('_row_number_ <= 2) // allowed duplication = 2
     +- Window [row_number() windowspecdefinition('a, 'b, 'a ASC NULLS FIRST, 'b ASC NULLS FIRST, specifiedwindowframe(RowFrame, unboundedpreceding$(), currentrow$())) AS _row_number_], ['a, 'b], ['a ASC NULLS FIRST, 'b ASC NULLS FIRST]
         +- Filter (isnotnull('a) AND isnotnull('b)) // keepempty=false
            +- Project
               +- UnresolvedRelation
  ```
+ `| dedup 2 a, b keepempty=true`의 경우

  ```
  Union
  :- DataFrameDropColumns('_row_number_)
  :  +- Filter ('_row_number_ <= 2)
  :     +- Window [row_number() windowspecdefinition('a, 'b, 'a ASC NULLS FIRST, 'b ASC NULLS FIRST, specifiedwindowframe(RowFrame, unboundedpreceding$(), currentrow$())) AS _row_number_], ['a, 'b], ['a ASC NULLS FIRST, 'b ASC NULLS FIRST]
  :        +- Filter (isnotnull('a) AND isnotnull('b))
  :           +- Project
  :              +- UnresolvedRelation
  +- Filter (isnull('a) OR isnull('b))
     +- Project
        +- UnresolvedRelation
  ```

#### describe 명령
<a name="supported-ppl-describe-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`describe` 명령을 사용하여 테이블, 스키마 및 카탈로그의 구조와 메타데이터에 대한 자세한 정보를 가져옵니다. 다음은 `describe` 명령의 다양한 예와 사용 사례입니다.

**설명**
+ `describe table` 이 명령은 `DESCRIBE EXTENDED table` SQL 명령과 같습니다.
+ `describe schema.table`
+ `describe schema.`table``
+ `describe catalog.schema.table`
+ `describe catalog.schema.`table``
+ `describe `catalog`.`schema`.`table``

#### eval 명령
<a name="supported-ppl-eval-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`eval` 명령은 표현식을 평가하고 검색 결과에 결과를 추가합니다.

**구문**  
다음 구문을 사용합니다.

```
eval <field>=<expression> ["," <field>=<expression> ]...    
```
+ `field`: 필수입니다. 필드 이름이 없으면 새 필드가 추가됩니다. 필드 이름이 이미 있는 경우 재정의됩니다.
+  `expression`: 필수입니다. 시스템에서 지원하는 모든 표현식입니다.

**예 1: 새 필드 생성**  
이 예에서는 각 문서에 대해 새 `doubleAge` 필드를 생성하는 방법을 보여줍니다. 새 `doubleAge`는 연령에 2를 곱한 평가 결과입니다.

PPL 쿼리:

```
os> source=accounts | eval doubleAge = age * 2 | fields age, doubleAge ;
fetched rows / total rows = 4/4
+-------+-------------+
| age   | doubleAge   |
|-------+-------------|
| 32    | 64          |
| 36    | 72          |
| 28    | 56          |
| 33    | 66          |
+-------+-------------+
```

**예 2: 기존 필드 재정의**  
이 예에서는 기존 연령 필드를 경과 시간에 1을 더한 값으로 재정의하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | eval age = age + 1 | fields age ;
fetched rows / total rows = 4/4
+-------+
| age   |
|-------|
| 33    |
| 37    |
| 29    |
| 34    |
+-------+
```

**예 3: eval에 정의된 필드를 사용하여 새 필드 생성**  
이 예에서는 eval 명령에 정의된 `ddAge` 필드를 사용하여 새 필드를 생성하는 방법을 보여줍니다. 새 필드 `ddAge`는 `doubleAge`의 평가 결과에 2를 곱한 값입니다. 여기서 `doubleAge`는 eval 명령에 정의되어 있습니다.

PPL 쿼리:

```
os> source=accounts | eval doubleAge = age * 2, ddAge = doubleAge * 2 | fields age, doubleAge, ddAge ;
fetched rows / total rows = 4/4
+-------+-------------+---------+
| age   | doubleAge   | ddAge   |
|-------+-------------+---------|
| 32    | 64          | 128     |
| 36    | 72          | 144     |
| 28    | 56          | 112     |
| 33    | 66          | 132     |
+-------+-------------+---------+
```

가정: `a`, `b`, `c`는 `table`의 기존 필드입니다.

**추가 예제**
+ `source = table | eval f = 1 | fields a,b,c,f`
+ `source = table | eval f = 1`(출력 a,b,c,f 필드)
+ `source = table | eval n = now() | eval t = unix_timestamp(a) | fields n,t`
+ `source = table | eval f = a | where f > 1 | sort f | fields a,b,c | head 5`
+ `source = table | eval f = a * 2 | eval h = f * 2 | fields a,f,h`
+ `source = table | eval f = a * 2, h = f * 2 | fields a,f,h`
+ `source = table | eval f = a * 2, h = b | stats avg(f) by h`
+ `source = table | eval f = ispresent(a)`
+ `source = table | eval r = coalesce(a, b, c) | fields r`
+ `source = table | eval e = isempty(a) | fields e`
+ `source = table | eval e = isblank(a) | fields e`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one', a = 2, 'two', a = 3, 'three', a = 4, 'four', a = 5, 'five', a = 6, 'six', a = 7, 'se7en', a = 8, 'eight', a = 9, 'nine')`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one' else 'unknown')`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one' else concat(a, ' is an incorrect binary digit'))`
+ `source = table | eval f = a in ('foo', 'bar') | fields f`
+ `source = table | eval f = a not in ('foo', 'bar') | fields f`

**case를 사용한 평가 예:**  


```
source = table | eval e = eval status_category =
case(a >= 200 AND a < 300, 'Success',
a >= 300 AND a < 400, 'Redirection',
a >= 400 AND a < 500, 'Client Error',
a >= 500, 'Server Error'
else 'Unknown')
```

**다른 case를 사용한 평가 예:**  


가정: `a`, `b`, `c`는 `table`의 기존 필드입니다.

**추가 예제**
+ `source = table | eval f = 1 | fields a,b,c,f`
+ `source = table | eval f = 1`(출력 a,b,c,f 필드)
+ `source = table | eval n = now() | eval t = unix_timestamp(a) | fields n,t`
+ `source = table | eval f = a | where f > 1 | sort f | fields a,b,c | head 5`
+ `source = table | eval f = a * 2 | eval h = f * 2 | fields a,f,h`
+ `source = table | eval f = a * 2, h = f * 2 | fields a,f,h`
+ `source = table | eval f = a * 2, h = b | stats avg(f) by h`
+ `source = table | eval f = ispresent(a)`
+ `source = table | eval r = coalesce(a, b, c) | fields r`
+ `source = table | eval e = isempty(a) | fields e`
+ `source = table | eval e = isblank(a) | fields e`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one', a = 2, 'two', a = 3, 'three', a = 4, 'four', a = 5, 'five', a = 6, 'six', a = 7, 'se7en', a = 8, 'eight', a = 9, 'nine')`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one' else 'unknown')`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one' else concat(a, ' is an incorrect binary digit'))`
+ `source = table | eval f = a in ('foo', 'bar') | fields f`
+ `source = table | eval f = a not in ('foo', 'bar') | fields f`

**case를 사용한 평가 예:**  


```
source = table | eval e = eval status_category =
case(a >= 200 AND a < 300, 'Success',
a >= 300 AND a < 400, 'Redirection',
a >= 400 AND a < 500, 'Client Error',
a >= 500, 'Server Error'
else 'Unknown')
```

**다른 case를 사용한 평가 예:**  


```
source = table |  where ispresent(a) |
eval status_category =
 case(a >= 200 AND a < 300, 'Success',
  a >= 300 AND a < 400, 'Redirection',
  a >= 400 AND a < 500, 'Client Error',
  a >= 500, 'Server Error'
  else 'Incorrect HTTP status code'
 )
 | stats count() by status_category
```

**제한 사항**
+ 기존 필드 재정의는 지원되지 않습니다. 쿼리에서 이렇게 하려고 시도하면 'Reference 'a' is ambiguous' 메시지와 함께 예외가 발생합니다.

  ```
  - `source = table | eval a = 10 | fields a,b,c`
  - `source = table | eval a = a * 2 | stats avg(a)`
  - `source = table | eval a = abs(a) | where a > 0`
  - `source = table | eval a = signum(a) | where a < 0`
  ```

#### eventstats 명령
<a name="supported-ppl-eventstats-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`eventstats` 명령을 사용하여 계산된 요약 통계로 이벤트 데이터를 보강합니다. 이벤트 내에 지정된 필드를 분석하고 다양한 통계 측정값을 계산한 다음, 그 결과를 각 원래 이벤트에 새 필드로 추가하는 식으로 작동합니다.

**eventstats의 주요 측면**

1. 전체 결과 집합 또는 정의된 그룹 내에서 계산을 수행합니다.

1. 원래 이벤트는 그대로 유지되며 통계 결과를 포함하도록 새 필드가 추가됩니다.

1. 명령은 비교 분석, 이상치 식별 또는 개별 이벤트에 대한 추가 컨텍스트 제공에 특히 유용합니다.

**통계와 이벤트 통계의 차이**  
`stats` 및 `eventstats` 명령은 모두 통계를 계산하는 데 사용되지만, 작동 방식과 생성되는 항목에 몇 가지 중요한 차이점이 있습니다.

**출력 형식**
+ `stats`: 계산된 통계만 포함된 요약 테이블을 생성합니다.
+ `eventstats`: 계산된 통계를 기존 이벤트에 새 필드로 추가하여 원래 데이터를 보존합니다.

**이벤트 보존**
+ `stats`: 결과 세트를 통계 요약으로만 줄여 개별 이벤트를 삭제합니다.
+ `eventstats`: 모든 원래 이벤트를 유지하고 계산된 통계와 함께 새 필드를 추가합니다.

**사용 사례**
+ `stats`: 요약 보고서 또는 대시보드를 생성하는 데 가장 적합합니다. 결과를 요약하는 최종 명령으로 자주 사용됩니다.
+ `eventstats`: 추가 분석 또는 필터링을 위해 통계 컨텍스트로 이벤트를 보강해야 할 때 유용합니다. 검색 중 후속 명령에 사용할 수 있는 통계를 추가하는 데 사용할 수 있습니다.

**구문**  
다음 구문을 사용합니다.

```
eventstats <aggregation>... [by-clause]    
```

**aggregation**
+ 필수.
+ 새 집계 함수.
+ 집계의 인수는 필드여야 합니다.

**by-clause**
+ 선택 사항.
+ 구문: `by [span-expression,] [field,]...`
+ by 절에는 스칼라 함수 및 집계 함수와 같은 필드와 표현식이 포함될 수 있습니다. span 절을 사용하여 특정 필드를 동일한 간격의 버킷으로 분할할 수도 있습니다. 그런 다음 eventstats 명령은 이러한 span 버킷을 기반으로 집계를 수행합니다.
+ 기본값: by 절을 지정하지 않으면 eventstats 명령이 전체 결과 집합에 걸쳐 집계됩니다.

**span 표현식**
+ 선택 사항, 최대 1개.
+ 구문: `span(field_expr, interval_expr)`
+ interval 표현식의 단위는 기본적으로 자연 단위입니다. 단, 날짜 및 시간 유형 필드의 경우 날짜/시간 단위를 사용할 때 간격 표현식에 단위를 지정해야 합니다.

  예를 들어 `age` 필드를 10년 단위의 버킷으로 분할하려면 `span(age, 10)`을 사용합니다. 시간 기반 필드의 경우 `span(timestamp, 1h)`을 사용하여 `timestamp` 필드를 시간별 간격으로 분할할 수 있습니다.


**사용 가능한 시간 단위**  

| 범위 간격 단위 | 
| --- | 
| 밀리초(ms) | 
| 초(초) | 
| 분(m, 대소문자 구분) | 
| 시간(h) | 
| 일(d) | 
| 주(w) | 
| 월(M, 대소문자 구분) | 
| 분기(q) | 
| 년(y) | 

**집계 함수**  


**`COUNT`**  
`COUNT`는 SELECT 문으로 검색된 행의 expr 수를 반환합니다.

CloudWatch Logs에서 쿼리를 사용하는 경우 `COUNT`는 지원되지 않습니다.

예제:

```
os> source=accounts | eventstats count();
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+--------------------+------------+--------------------------+--------+-------+---------+
| account_number | balance  | firstname | lastname | age | gender | address            | employer   | email                    | city   | state | count() |
+----------------+----------+-----------+----------+-----+--------+--------------------+------------+--------------------------+--------+-------+---------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | *** Any Lane       | AnyCorp    | janedoe@anycorp.com      | Brogan | IL    | 4       |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street | AnyCompany | marymajor@anycompany.com | Dante  | TN    | 4       |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street     | AnyOrg     |                          | Nogal  | VA    | 4       |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court  |            | juanli@exampleorg.com    | Orick  | MD    | 4       |
+----------------+----------+-----------+----------+-----+--------+--------------------+------------+--------------------------+--------+-------+---------+
```

**`SUM`**  
`SUM(expr)`은 expr의 합계를 반환합니다.

예제:

```
os> source=accounts | eventstats sum(age) by gender;
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+------------+--------------------------+--------+-------+--------------------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer   | email                    | city   | state | sum(age) by gender |
+----------------+----------+-----------+----------+-----+--------+-----------------------+------------+--------------------------+--------+-------+--------------------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | 880 Any Lane          | AnyCorp    | janedoe@anycorp.com      | Brogan | IL    | 101                |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | AnyCompany | marymajor@anycompany.com | Dante  | TN    | 101                |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street        | AnyOrg     |                          | Nogal  | VA    | 28                 |
| 18             | 4180     | Juan      | Li       | 33  | M      | 467 Example Court     |            | juanli@exampleorg.com    | Orick  | MD    | 101                |
+----------------+----------+-----------+----------+-----+--------+-----------------------+------------+--------------------------+--------+-------+--------------------+
```

**`AVG`**  
`AVG(expr)`는 expr의 평균 값을 반환합니다.

예제:

```
os> source=accounts | eventstats avg(age) by gender;
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+------------+---------------------------+--------+-------+--------------------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | avg(age) by gender |
+----------------+----------+-----------+----------+-----+--------+-----------------------+------------+---------------------------+--------+-------+--------------------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | 880 Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 33.67              |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 33.67              |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street        | AnyOrg      |                          | Nogal  | VA    | 28.00              |
| 18             | 4180     | Juan      | Li       | 33  | M      | 467 Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 33.67              |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+--------------------+
```

**MAX**  
`MAX(expr)`는 expr의 최대값을 반환합니다.

예제

```
os> source=accounts | eventstats max(age);
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | max(age)  |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | 880 Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 36        |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 36        |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street        | AnyOrg      |                          | Nogal  | VA    | 36        |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 36        |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+
```

**MIN**  
`MIN(expr)`은 expr의 최소값을 반환합니다.

예제

```
os> source=accounts | eventstats min(age);
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | min(age)  |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | 880 Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 28        |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 28        |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | *** Any Street        | AnyOrg      |                          | Nogal  | VA    | 28        |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 28        |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+
```

**STDDEV\$1SAMP**  
`STDDEV_SAMP(expr)`는 expr의 샘플 표준 편차를 반환합니다.

예제

```
os> source=accounts | eventstats stddev_samp(age);
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+------------------------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | stddev_samp(age)       |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+------------------------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | *** Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 3.304037933599835      |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 3.304037933599835      |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street        | AnyOrg      |                          | Nogal  | VA    | 3.304037933599835      |
| 18             | 4180     | Juan      | Li       | 33  | M      | 467 Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 3.304037933599835      |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+------------------------+
```

**STDDEV\$1POP**  
`STDDEV_POP(expr)`는 expr의 모집단 표준 편차를 반환합니다.

예제

```
os> source=accounts | eventstats stddev_pop(age);
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+------------------------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | stddev_pop(age)        |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+------------------------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | 880 Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 2.****************     |
| 6              | 5686     | Mary      | Major    | 36  | M      | *** Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 2.****************     |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | *** Any Street        | AnyOrg      |                          | Nogal  | VA    | 2.****************     |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 2.****************     |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+------------------------+
```

**PERCENTILE 또는 PERCENTILE\$1APPROX**  
`PERCENTILE(expr, percent)` 또는 `PERCENTILE_APPROX(expr, percent)`는 expr의 대략적인 백분위수 값을 지정된 백분율로 반환합니다.

**%**
+ 숫자는 0에서 100 사이의 상수여야 합니다.

예제

```
os> source=accounts | eventstats percentile(age, 90) by gender;
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+--------------------------------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | percentile(age, 90) by gender  |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+--------------------------------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | *** Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 36                             |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 36                             |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street        | AnyOrg      |                          | Nogal  | VA    | 28                             |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 36                             |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+--------------------------------+
```

**예 1: 그룹별 필드의 평균, 합계 및 개수 계산**  
이 예에서는 성별을 기준으로 모든 계정 그룹의 평균 연령, 합계 연령 및 이벤트 수를 계산합니다.

```
os> source=accounts | eventstats avg(age) as avg_age, sum(age) as sum_age, count() as count by gender;
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+-----------+-------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | avg_age   | sum_age   | count |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+-----------+-------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | *** Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 33.666667 | 101       | 3     |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 33.666667 | 101       | 3     |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street        | AnyOrg      |                          | Nogal  | VA    | 28.000000 | 28        | 1     |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 33.666667 | 101       | 3     |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+-----------+-----------+-------+
```

**예 2: 범위별로 개수 계산**  
이 예에서는 연령을 10년 간격으로 가져옵니다.

```
os> source=accounts | eventstats count(age) by span(age, 10) as age_span
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+----------+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                    | city   | state | age_span |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+----------+
| 1              | 39225    | Jane      | Doe      | 32  | M      | *** Any Lane          | AnyCorp     | janedoe@anycorp.com      | Brogan | IL    | 3        |
| 6              | 5686     | Mary      | Major    | 36  | M      | 671 Example Street    | Any Company | marymajor@anycompany.com | Dante  | TN    | 3        |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | 789 Any Street        | AnyOrg      |                          | Nogal  | VA    | 1        |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court     |             | juanli@exampleorg.com    | Orick  | MD    | 3        |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+--------------------------+--------+-------+----------+
```

**예 3: 성별 및 범위별로 개수 계산**  
이 예에서는 연령을 5년 간격으로 구하고 성별로 그룹화합니다.

```
os> source=accounts | eventstats count() as cnt by span(age, 5) as age_span, gender
fetched rows / total rows = 4/4
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+---------------------------+--------+-------+-----+
| account_number | balance  | firstname | lastname | age | gender | address               | employer    | email                     | city   | state | cnt |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+---------------------------+--------+-------+-----+
| 1              | 39225    | Jane      | Doe      | 32  | M      | *** Any Lane          | AnyCorp     | janedoe@anycorp.com       | Brogan | IL    | 2   |
| 6              | 5686     | Mary      | Majo     | 36  | M      | 671 Example Street    | Any Company | hattiebond@anycompany.com | Dante  | TN    | 1   |
| 13             | 32838    | Nikki     | Wolf     | 28  | F      | *** Any Street        | AnyOrg      |                           | Nogal  | VA    | 1   |
| 18             | 4180     | Juan      | Li       | 33  | M      | *** Example Court     |             | juanli@exampleorg.com     | Orick  | MD    | 2   |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+---------------------------+--------+-------+-----+
```

**사용법**
+ `source = table | eventstats avg(a)`
+ `source = table | where a < 50 | eventstats avg(c)`
+ `source = table | eventstats max(c) by b`
+ `source = table | eventstats count(c) by b | head 5`
+ `source = table | eventstats distinct_count(c)`
+ `source = table | eventstats stddev_samp(c)`
+ `source = table | eventstats stddev_pop(c)`
+ `source = table | eventstats percentile(c, 90)`
+ `source = table | eventstats percentile_approx(c, 99)`

**범위를 사용한 집계**  

+ `source = table | eventstats count(a) by span(a, 10) as a_span`
+ `source = table | eventstats sum(age) by span(age, 5) as age_span | head 2`
+ `source = table | eventstats avg(age) by span(age, 20) as age_span, country | sort - age_span | head 2`

**기간 범위를 사용한 집계(텀블 윈도우 함수)**  

+ `source = table | eventstats sum(productsAmount) by span(transactionDate, 1d) as age_date | sort age_date`
+ `source = table | eventstats sum(productsAmount) by span(transactionDate, 1w) as age_date, productId`

**여러 수준별 집계 그룹**  

+ `source = table | eventstats avg(age) as avg_state_age by country, state | eventstats avg(avg_state_age) as avg_country_age by country`
+ `source = table | eventstats avg(age) as avg_city_age by country, state, city | eval new_avg_city_age = avg_city_age - 1 | eventstats avg(new_avg_city_age) as avg_state_age by country, state | where avg_state_age > 18 | eventstats avg(avg_state_age) as avg_adult_country_age by country`

#### expand 명령
<a name="supported-ppl-expand-commands"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`expand` 명령을 사용하여 다음 유형의 필드를 평면화합니다.
+ `Array<Any>`
+ `Map<Any>`

**구문**  
다음 구문을 사용합니다.

```
expand <field> [As alias]
```

**필드**
+ 확장할 필드입니다. 지원되는 유형이어야 합니다.

**별칭**
+ 선택 사항. 원래 필드 이름 대신 사용할 이름입니다.

**사용법**  
이 `expand` 명령은 지정된 배열 또는 맵 필드의 각 요소에 해당하는 행을 생성합니다.
+ 배열 요소는 개별 행이 됩니다.
+ 맵 키-값 페어는 별도의 행으로 나뉘며 각 키-값은 행으로 표시됩니다.
+ 별칭이 제공되면 분해된 값이 원래 필드 이름 대신 별칭 아래에 표시됩니다.
+ 이는 `stats`, `eval`, `parse` 등의 다른 명령과 함께 확장 후 데이터를 조작하거나 추출하는 데 사용할 수 있습니다.

**예제**
+ `source = table | expand employee | stats max(salary) as max by state, company`
+ `source = table | expand employee as worker | stats max(salary) as max by state, company`
+ `source = table | expand employee as worker | eval bonus = salary * 3 | fields worker, bonus`
+ `source = table | expand employee | parse description '(?<email>.+@.+)' | fields employee, email`
+ `source = table | eval array=json_array(1, 2, 3) | expand array as uid | fields name, occupation, uid`
+ `source = table | expand multi_valueA as multiA | expand multi_valueB as multiB`

#### explain 명령
<a name="supported-ppl-explain-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`explain` 명령은 쿼리 실행 계획을 이해하는 데 도움이 되므로 쿼리를 분석하고 최적화하여 성능을 높일 수 있습니다. 이 소개에서는 쿼리 최적화에서 설명 명령의 용도와 중요도에 대한 간략한 개요를 제공합니다.

**설명**
+ `source=accounts | top gender // finds most common gender of all the accounts`(줄 주석)
+ `source=accounts | dedup 2 gender /* dedup the document with gender field keep 2 duplication */ | fields account_number, gender`(블록 주석)

**설명**
+ `describe table` 이 명령은 `DESCRIBE EXTENDED table` SQL 명령과 같습니다.
+ `describe schema.table`
+ `describe schema.`table``
+ `describe catalog.schema.table`
+ `describe catalog.schema.`table``
+ `describe `catalog`.`schema`.`table``

**설명**
+ `explain simple | source = table | where a = 1 | fields a,b,c`
+ `explain extended | source = table`
+ `explain codegen | source = table | dedup a | fields a,b,c`
+ `explain cost | source = table | sort a | fields a,b,c`
+ `explain formatted | source = table | fields - a`
+ `explain simple | describe table`

**필드**
+ `source = table`
+ `source = table | fields a,b,c`
+ `source = table | fields + a,b,c`
+ `source = table | fields - b,c`
+ `source = table | eval b1 = b | fields - b1,c`

**필드 요약**
+ `source = t | fieldsummary includefields=status_code nulls=false`
+ `source = t | fieldsummary includefields= id, status_code, request_path nulls=true`
+ `source = t | where status_code != 200 | fieldsummary includefields= status_code nulls=true`

**중첩 필드**
+ `source = catalog.schema.table1, catalog.schema.table2 | fields A.nested1, B.nested1`
+ `source = catalog.table | where struct_col2.field1.subfield > 'valueA' | sort int_col | fields int_col, struct_col.field1.subfield, struct_col2.field1.subfield`
+ `source = catalog.schema.table | where struct_col2.field1.subfield > 'valueA' | sort int_col | fields int_col, struct_col.field1.subfield, struct_col2.field1.subfield`

**필터**
+ `source = table | where a = 1 | fields a,b,c`
+ `source = table | where a >= 1 | fields a,b,c`
+ `source = table | where a < 1 | fields a,b,c`
+ `source = table | where b != 'test' | fields a,b,c`
+ `source = table | where c = 'test' | fields a,b,c | head 3`
+ `source = table | where ispresent(b)`
+ `source = table | where isnull(coalesce(a, b)) | fields a,b,c | head 3`
+ `source = table | where isempty(a)`
+ `source = table | where isblank(a)`
+ `source = table | where case(length(a) > 6, 'True' else 'False') = 'True'`
+ `source = table | where a not in (1, 2, 3) | fields a,b,c`
+ `source = table | where a between 1 and 4` - 참고 :이 값은 >= 1 및 <= 4, 즉 [1, 4]를 반환합니다.
+ `source = table | where b not between '2024-09-10' and '2025-09-10'` - 참고: b >= '\$1\$1\$1\$1\$1\$1\$1\$1\$1\$1' 및 b <= '2025-09-10'을 반환합니다.
+ `source = table | where cidrmatch(ip, '***********/24')`
+ `source = table | where cidrmatch(ipv6, '2003:db8::/32')`
+ `source = table | trendline sma(2, temperature) as temp_trend`

**IP 관련 쿼리**
+ `source = table | where cidrmatch(ip, '**************')`
+ `source = table | where isV6 = false and isValid = true and cidrmatch(ipAddress, '**************')`
+ `source = table | where isV6 = true | eval inRange = case(cidrmatch(ipAddress, '2003:***::/32'), 'in' else 'out') | fields ip, inRange`

**복잡한 필터**  


```
source = table | eval status_category =
case(a >= 200 AND a < 300, 'Success',
    a >= 300 AND a < 400, 'Redirection',
    a >= 400 AND a < 500, 'Client Error',
    a >= 500, 'Server Error'
else 'Incorrect HTTP status code')
| where case(a >= 200 AND a < 300, 'Success',
    a >= 300 AND a < 400, 'Redirection',
    a >= 400 AND a < 500, 'Client Error',
    a >= 500, 'Server Error'
else 'Incorrect HTTP status code'
) = 'Incorrect HTTP status code'
```

```
source = table
| eval factor = case(a > 15, a - 14, isnull(b), a - 7, a < 3, a + 1 else 1)
| where case(factor = 2, 'even', factor = 4, 'even', factor = 6, 'even', factor = 8, 'even' else 'odd') = 'even'
| stats count() by factor
```

**논리적 조건이 있는 필터**
+ `source = table | where c = 'test' AND a = 1 | fields a,b,c`
+ `source = table | where c != 'test' OR a > 1 | fields a,b,c | head 1`
+ `source = table | where c = 'test' NOT a > 1 | fields a,b,c`

**Eval**  
가정: `a`, `b`, `c`는 `table`의 기존 필드입니다.
+ `source = table | eval f = 1 | fields a,b,c,f`
+ `source = table | eval f = 1`(출력 a,b,c,f 필드)
+ `source = table | eval n = now() | eval t = unix_timestamp(a) | fields n,t`
+ `source = table | eval f = a | where f > 1 | sort f | fields a,b,c | head 5`
+ `source = table | eval f = a * 2 | eval h = f * 2 | fields a,f,h`
+ `source = table | eval f = a * 2, h = f * 2 | fields a,f,h`
+ `source = table | eval f = a * 2, h = b | stats avg(f) by h`
+ `source = table | eval f = ispresent(a)`
+ `source = table | eval r = coalesce(a, b, c) | fields r`
+ `source = table | eval e = isempty(a) | fields e`
+ `source = table | eval e = isblank(a) | fields e`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one', a = 2, 'two', a = 3, 'three', a = 4, 'four', a = 5, 'five', a = 6, 'six', a = 7, 'se7en', a = 8, 'eight', a = 9, 'nine')`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one' else 'unknown')`
+ `source = table | eval f = case(a = 0, 'zero', a = 1, 'one' else concat(a, ' is an incorrect binary digit'))`
+ `source = table | eval digest = md5(fieldName) | fields digest`
+ `source = table | eval digest = sha1(fieldName) | fields digest`
+ `source = table | eval digest = sha2(fieldName,256) | fields digest`
+ `source = table | eval digest = sha2(fieldName,512) | fields digest`

#### fillnull 명령
<a name="supported-ppl-fillnull-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

**설명**  
`fillnull` 명령을 사용하여 검색 결과의 필드 하나 이상에서 null 값을 지정된 값으로 바꿉니다.

**구문**  
다음 구문을 사용합니다.

```
fillnull [with <null-replacement> in <nullable-field>["," <nullable-field>]] | [using <source-field> = <null-replacement> [","<source-field> = <null-replacement>]]
```
+ null-replacement: 필수. null 값을 대체하는 데 사용되는 값입니다.
+ nullable-field: 필수. 필드 참조입니다. 이 필드의 null 값이 null-replacement에 지정된 값으로 대체됩니다.

**예 1: 단일 필드의 Fillnull**  
이 예는 단일 필드에서 fillnull을 사용하는 방법을 보여줍니다.

```
os> source=logs | fields status_code | eval input=status_code | fillnull with 0 in status_code;
| input | status_code |
|-------|-------------|
| 403   | 403         |
| 403   | 403         |
| NULL  | 0           |
| NULL  | 0           |
| 200   | 200         |
| 404   | 404         |
| 500   | 500         |
| NULL  | 0           |
| 500   | 500         |
| 404   | 404         |
| 200   | 200         |
| 500   | 500         |
| NULL  | 0           |
| NULL  | 0           |
| 404   | 404         |
```

**예 2: 여러 필드에 적용된 Fillnull**  
이 예는 여러 필드에 적용된 fillnull을 보여줍니다.

```
os> source=logs | fields request_path, timestamp | eval input_request_path=request_path, input_timestamp = timestamp | fillnull with '???' in request_path, timestamp;
| input_request_path | input_timestamp       | request_path | timestamp              |
|------------------------------------------------------------------------------------|
| /contact           | NULL                  | /contact     | ???                    |
| /home              | NULL                  | /home        | ???                    |
| /about             | 2023-10-01 10:30:00   | /about       | 2023-10-01 10:30:00    |
| /home              | 2023-10-01 10:15:00   | /home        | 2023-10-01 10:15:00    |
| NULL               | 2023-10-01 10:20:00   | ???          | 2023-10-01 10:20:00    |
| NULL               | 2023-10-01 11:05:00   | ???          | 2023-10-01 11:05:00    |
| /about             | NULL                  | /about       | ???                    |
| /home              | 2023-10-01 10:00:00   | /home        | 2023-10-01 10:00:00    |
| /contact           | NULL                  | /contact     | ???                    |
| NULL               | 2023-10-01 10:05:00   | ???          | 2023-10-01 10:05:00    |
| NULL               | 2023-10-01 10:50:00   | ???          | 2023-10-01 10:50:00    |
| /services          | NULL                  | /services    | ???                    |
| /home              | 2023-10-01 10:45:00   | /home        | 2023-10-01 10:45:00    |
| /services          | 2023-10-01 11:00:00   | /services    | 2023-10-01 11:00:00    |
| NULL               | 2023-10-01 10:35:00   | ???          | 2023-10-01 10:35:00    |
```

**예 3: 다양한 null 대체 값을 사용하여 여러 필드에 적용된 Fillnull.**  
이 예에서는 null을 대체하는 데 사용되는 다양한 값이 있는 fillnull을 보여줍니다.
+ `request_path` 필드의 `/error`
+ `timestamp` 필드의 `1970-01-01 00:00:00`

```
os> source=logs | fields request_path, timestamp | eval input_request_path=request_path, input_timestamp = timestamp | fillnull using request_path = '/error', timestamp='1970-01-01 00:00:00';

| input_request_path | input_timestamp       | request_path | timestamp              |
|------------------------------------------------------------------------------------|
| /contact           | NULL                  | /contact     | 1970-01-01 00:00:00    |
| /home              | NULL                  | /home        | 1970-01-01 00:00:00    |
| /about             | 2023-10-01 10:30:00   | /about       | 2023-10-01 10:30:00    |
| /home              | 2023-10-01 10:15:00   | /home        | 2023-10-01 10:15:00    |
| NULL               | 2023-10-01 10:20:00   | /error       | 2023-10-01 10:20:00    |
| NULL               | 2023-10-01 11:05:00   | /error       | 2023-10-01 11:05:00    |
| /about             | NULL                  | /about       | 1970-01-01 00:00:00    |
| /home              | 2023-10-01 10:00:00   | /home        | 2023-10-01 10:00:00    |
| /contact           | NULL                  | /contact     | 1970-01-01 00:00:00    |
| NULL               | 2023-10-01 10:05:00   | /error       | 2023-10-01 10:05:00    |
| NULL               | 2023-10-01 10:50:00   | /error       | 2023-10-01 10:50:00    |
| /services          | NULL                  | /services    | 1970-01-01 00:00:00    |
| /home              | 2023-10-01 10:45:00   | /home        | 2023-10-01 10:45:00    |
| /services          | 2023-10-01 11:00:00   | /services    | 2023-10-01 11:00:00    |
| NULL               | 2023-10-01 10:35:00   | /error       | 2023-10-01 10:35:00    |
```

#### fields 명령
<a name="supported-ppl-fields-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`fields` 명령을 사용하여 검색 결과에서 필드를 유지하거나 제거합니다.

**구문**  
다음 구문을 사용합니다.

```
field [+|-] <field-list> 
```
+ `index`: 선택 사항입니다.

  더하기(\$1)를 사용하는 경우 필드 목록에 지정된 필드만 유지됩니다.

  마이너스(-)를 사용하면 필드 목록에 지정된 모든 필드가 제거됩니다.

  *기본값*: \$1
+ `field list`: 필수입니다. 쉼표로 구분된, 유지하거나 제거할 필드의 목록입니다.

**예 1: 결과에서 지정된 필드 선택**  
이 예에서는 검색 결과에서 `account_number`, `firstname` 및 `lastname` 필드를 가져오는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | fields account_number, firstname, lastname;
fetched rows / total rows = 4/4
+------------------+-------------+------------+
| account_number   | firstname   | lastname   |
|------------------+-------------+------------|
| 1                | Jane        | Doe        |
| 6                | John        | Doe        |
| 13               | Jorge       | Souza      |
| 18               | Juan        | Li         |
+------------------+-------------+------------+
```

**예 2: 결과에서 지정된 필드 제거**  
이 예에서는 검색 결과에서 `account_number` 필드를 제거하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | fields account_number, firstname, lastname | fields - account_number ;
fetched rows / total rows = 4/4
+-------------+------------+
| firstname   | lastname   |
|-------------+------------|
| Jane        | Doe        |
| John        | Doe        |
| Jorge       | Souza      |
| Juan        | Li         |
+-------------+------------+
```

**추가 예제**
+ `source = table`
+ `source = table | fields a,b,c`
+ `source = table | fields + a,b,c`
+ `source = table | fields - b,c`
+ `source = table | eval b1 = b | fields - b1,c`

중첩 필드 예:

```
`source = catalog.schema.table1, catalog.schema.table2 | fields A.nested1, B.nested1`
`source = catalog.table | where struct_col2.field1.subfield > 'valueA' | sort int_col | fields  int_col, struct_col.field1.subfield, struct_col2.field1.subfield`
`source = catalog.schema.table | where struct_col2.field1.subfield > 'valueA' | sort int_col | fields  int_col, struct_col.field1.subfield, struct_col2.field1.subfield`
```

#### flatten 명령
<a name="supported-ppl-flatten-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

flatten 명령을 사용하여 다음 유형의 필드를 확장합니다.
+ `struct<?,?>`
+ `array<struct<?,?>>`

**구문**  
다음 구문을 사용합니다.

```
flatten <field>
```
+ *field*: 평면화할 필드입니다. 필드는 지원되는 유형이어야 합니다.

**스키마**


| col\$1name | data\$1type | 
| --- | --- | 
| \$1time | 문자열 | 
| bridges | array<struct<length:bigint,name:string>> | 
| city | 문자열 | 
| coor | struct<alt:bigint,lat:double,long:double> | 
| country | 문자열 | 

**데이터**  



| \$1time | bridges | city | coor | country | 
| --- | --- | --- | --- | --- | 
| 2024-09-13T12:00:00 | [\$1801, Tower Bridge\$1, \$1928, London Bridge\$1] | 런던 | \$135, 51.5074, -0.1278\$1 | 영국 | 
| 2024-09-13T12:00:00 | [\$1232, Pont Neuf\$1, \$1160, Pont Alexandre III\$1] | 파리 | \$135, 48.8566, 2.3522\$1 | 프랑스 | 
| 2024-09-13T12:00:00 | [\$148, Rialto Bridge\$1, \$111, Bridge of Sighs\$1] | Venice | \$12, 45.4408, 12.3155\$1 | 이탈리아 | 
| 2024-09-13T12:00:00 | [\$1\$1\$1\$1, Charles Bridge\$1, \$1343, Legion Bridge\$1] | Prague | \$1200, 50.0755, 14.4378\$1 | 체코 공화국 | 
| 2024-09-13T12:00:00 | [\$1375, Chain Bridge\$1, \$1333, Liberty Bridge\$1] | Budapest | \$196, 47.4979, 19.0402\$1 | 헝가리 | 
| 1990-09-13T12:00:00 | NULL | Warsaw | NULL | 폴란드 | 

**예 1: 구문 평면화**  
이 예에서는 구문 필드를 평면화하는 방법을 보여줍니다.

PPL 쿼리:

```
source=table | flatten coor
```


| \$1time | bridges | city | country | alt | lat | long | 
| --- | --- | --- | --- | --- | --- | --- | 
| 2024-09-13T12:00:00 | [\$1801, Tower Bridge\$1, \$1928, London Bridge\$1] | 런던 | 영국 | 35 | 51.5074 | -0.1278 | 
| 2024-09-13T12:00:00 | [\$1232, Pont Neuf\$1, \$1160, Pont Alexandre III\$1] | 파리 | 프랑스 | 35 | 48.8566 | 2.3522 | 
| 2024-09-13T12:00:00 | [\$148, Rialto Bridge\$1, \$111, Bridge of Sighs\$1] | Venice | 이탈리아 | 2 | 45.4408 | 12.3155 | 
| 2024-09-13T12:00:00 | [\$1516, Charles Bridge\$1, \$1343, Legion Bridge\$1] | Prague | 체코 공화국 | 200 | 50.0755 | 14.4378 | 
| 2024-09-13T12:00:00 | [\$1375, Chain Bridge\$1, \$1333, Liberty Bridge\$1] | Budapest | 헝가리 | 96 | 47.4979 | 19.0402 | 
| 1990-09-13T12:00:00 | NULL | Warsaw | 폴란드 | NULL | NULL | NULL | 

**예 2: 배열 평면화**  
이 예에서는 구문 필드 배열을 평면화하는 방법을 보여줍니다.

PPL 쿼리:

```
source=table | flatten bridges
```


| \$1time | city | coor | country | length | 이름 | 
| --- | --- | --- | --- | --- | --- | 
| 2024-09-13T12:00:00 | 런던 | \$135, 51.5074, -0.1278\$1 | 영국 | 801 | Tower Bridge | 
| 2024-09-13T12:00:00 | 런던 | \$135, 51.5074, -0.1278\$1 | 영국 | 928 | London Bridge | 
| 2024-09-13T12:00:00 | 파리 | \$135, 48.8566, 2.3522\$1 | 프랑스 | 232 | Pont Neuf | 
| 2024-09-13T12:00:00 | 파리 | \$135, 48.8566, 2.3522\$1 | 프랑스 | 160 | Pont Alexandre III | 
| 2024-09-13T12:00:00 | Venice | \$12, 45.4408, 12.3155\$1 | 이탈리아 | 48 | Rialto Bridge | 
| 2024-09-13T12:00:00 | Venice | \$12, 45.4408, 12.3155\$1 | 이탈리아 | 11 | Bridge of Sighs | 
| 2024-09-13T12:00:00 | Prague | \$1200, 50.0755, 14.4378\$1 | 체코 공화국 | 516 | Charles Bridge | 
| 2024-09-13T12:00:00 | Prague | \$1200, 50.0755, 14.4378\$1 | 체코 공화국 | 343 | Legion Bridge | 
| 2024-09-13T12:00:00 | Budapest | \$196, 47.4979, 19.0402\$1 | 헝가리 | 375 | Chain Bridge | 
| 2024-09-13T12:00:00 | Budapest | \$196, 47.4979, 19.0402\$1 | 헝가리 | 333 | Liberty Bridge | 
| 1990-09-13T12:00:00 | Warsaw | NULL | 폴란드 | NULL | NULL | 

**예 3: 배열 및 구문 평면화**  
이 예에서는 여러 필드를 평면화하는 방법을 보여줍니다.

PPL 쿼리:

```
source=table | flatten bridges | flatten coor
```


| \$1time | city | country | length | 이름 | alt | lat | long | 
| --- | --- | --- | --- | --- | --- | --- | --- | 
| 2024-09-13T12:00:00 | 런던 | 영국 | 801 | Tower Bridge | 35 | 51.5074 | -0.1278 | 
| 2024-09-13T12:00:00 | 런던 | 영국 | 928 | London Bridge | 35 | 51.5074 | -0.1278 | 
| 2024-09-13T12:00:00 | 파리 | 프랑스 | 232 | Pont Neuf | 35 | 48.8566 | 2.3522 | 
| 2024-09-13T12:00:00 | 파리 | 프랑스 | 160 | Pont Alexandre III | 35 | 48.8566 | 2.3522 | 
| 2024-09-13T12:00:00 | Venice | 이탈리아 | 48 | Rialto Bridge | 2 | 45.4408 | 12.3155 | 
| 2024-09-13T12:00:00 | Venice | 이탈리아 | 11 | Bridge of Sighs | 2 | 45.4408 | 12.3155 | 
| 2024-09-13T12:00:00 | Prague | 체코 공화국 | 516 | Charles Bridge | 200 | 50.0755 | 14.4378 | 
| 2024-09-13T12:00:00 | Prague | 체코 공화국 | 343 | Legion Bridge | 200 | 50.0755 | 14.4378 | 
| 2024-09-13T12:00:00 | Budapest | 헝가리 | 375 | Chain Bridge | 96 | 47.4979 | 19.0402 | 
| 2024-09-13T12:00:00 | Budapest | 헝가리 | 333 | Liberty Bridge | 96 | 47.4979 | 19.0402 | 
| 1990-09-13T12:00:00 | Warsaw | 폴란드 | NULL | NULL | NULL | NULL | NULL | 

#### grok 명령
<a name="supported-ppl-grok-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`grok` 명령은 grok 패턴으로 텍스트 필드를 구문 분석하고 그 결과를 검색 결과에 추가합니다.

**구문**  
다음 구문을 사용합니다.

```
grok <field> <pattern>
```

**필드**
+ 필수.
+ 필드는 텍스트 필드여야 합니다.

**pattern**
+ 필수.
+ 지정된 텍스트 필드에서 새 필드를 추출하는 데 사용되는 grok 패턴입니다.
+ 새 필드 이름이 이미 사용 중인 경우 원래 필드를 대체합니다.

**Grok 패턴**  
grok 패턴은 각 문서의 텍스트 필드와 매칭하여 새 필드를 추출하는 데 사용됩니다.

**예 1: 새 필드 생성**  
이 예에서는 각 문서에 대해 새 필드 `host`를 생성하는 방법을 보여줍니다. `host`는 `email` 필드에서 `@` 뒤에 오는 호스트 이름이 됩니다. null 필드를 구문 분석하면 빈 문자열이 반환됩니다.

```
os> source=accounts | grok email '.+@%{HOSTNAME:host}' | fields email, host ;
fetched rows / total rows = 4/4
+-------------------------+-------------+
| email                   | host        |
|-------------------------+-------------|
| jane_doe@example.com    | example.com |
| arnav_desai@example.net | example.net |
| null                    |             |
| juan_li@example.org     | example.org |
+-------------------------+-------------+
```

**예 2: 기존 필드 재정의**  
이 예에서는 번지가 제거된 기존 `address` 필드를 재정의하는 방법을 보여줍니다.

```
os> source=accounts | grok address '%{NUMBER} %{GREEDYDATA:address}' | fields address ;
fetched rows / total rows = 4/4
+------------------+
| address          |
|------------------|
| Example Lane     |
| Any Street       |
| Main Street      |
| Example Court    |
+------------------+
```

**예 3: grok을 사용하여 로그 구문 분석**  
이 예에서는 grok을 사용하여 원시 로그를 구문 분석하는 방법을 보여줍니다.

```
os> source=apache | grok message '%{COMMONAPACHELOG}' | fields COMMONAPACHELOG, timestamp, response, bytes ;
fetched rows / total rows = 4/4
+-----------------------------------------------------------------------------------------------------------------------------+----------------------------+------------+---------+
| COMMONAPACHELOG                                                                                                             | timestamp                  | response   | bytes   |
|-----------------------------------------------------------------------------------------------------------------------------+----------------------------+------------+---------|
| 177.95.8.74 - upton5450 [28/Sep/2022:10:15:57 -0700] "HEAD /e-business/mindshare HTTP/1.0" 404 19927                        | 28/Sep/2022:10:15:57 -0700 | 404        | 19927   |
| 127.45.152.6 - pouros8756 [28/Sep/2022:10:15:57 -0700] "GET /architectures/convergence/niches/mindshare HTTP/1.0" 100 28722 | 28/Sep/2022:10:15:57 -0700 | 100        | 28722   |
| *************** - - [28/Sep/2022:10:15:57 -0700] "PATCH /strategize/out-of-the-box HTTP/1.0" 401 27439                      | 28/Sep/2022:10:15:57 -0700 | 401        | 27439   |
| ************** - - [28/Sep/2022:10:15:57 -0700] "POST /users HTTP/1.1" 301 9481                                             | 28/Sep/2022:10:15:57 -0700 | 301        | 9481    |
+-----------------------------------------------------------------------------------------------------------------------------+----------------------------+------------+---------+
```

**제한 사항**  
grok 명령에는 구문 분석 명령과 동일한 제한 사항이 있습니다.

#### head 명령
<a name="supported-ppl-head-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`head` 명령을 사용하여 선택적 오프셋 뒤에 지정된 결과의 첫 N개를 검색 순서대로 반환합니다.

**구문**  
다음 구문을 사용합니다.

```
head [<size>] [from <offset>]
```

**<size>**
+ 선택 사항인 정수입니다.
+ 반환할 결과 수.
+ 기본값: 10

**<offset>**
+ 선택 사항인 `from` 이후의 정수입니다.
+ 건너뛸 결과 수입니다.
+ 기본값: 0

**예 1: 처음 10개의 결과 가져오기**  
이 예는 계정 인덱스에서 최대 10개의 결과를 검색하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | fields firstname, age | head;
fetched rows / total rows = 4/4
+-------------+-------+
| firstname   | age   |
|-------------+-------|
| Jane        | 32    |
| John        | 36    |
| Jorge       | 28    |
| Juan        | 33    |
+-------------+-------+
```

**예 2: 처음 N개의 결과 가져오기**  
이 예는 계정 인덱스의 처음 N개 결과를 보여줍니다.

PPL 쿼리:

```
os> source=accounts | fields firstname, age | head 3;
fetched rows / total rows = 3/3
+-------------+-------+
| firstname   | age   |
|-------------+-------|
| Jane        | 32    |
| John        | 36    |
| Jorge       | 28    |
+-------------+-------+
```

**예 3: 오프셋 M개 이후의 처음 N개 결과 가져오기**  
이 예에서는 계정 인덱스에서 M개 결과를 건너뛴 후 처음 N개 결과를 검색하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | fields firstname, age | head 3 from 1;
fetched rows / total rows = 3/3
+-------------+-------+
| firstname   | age   |
|-------------+-------|
| John        | 36    |
| Jorge       | 28    |
| Juan        | 33    |
+-------------+-------+
```

#### join 명령
<a name="supported-ppl-join-commands"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

join 명령을 사용하면 공통 필드를 기반으로 여러 소스의 데이터를 결합하여 복잡한 분석을 수행하고 분산 데이터 세트에서 심층적인 인사이트를 얻을 수 있습니다.

**스키마**  
인덱스는 최소 `otel-v1-apm-span-*`(large)와 `otel-v1-apm-service-map`(small)이 있습니다.

인덱스의 관련 필드:

**`otel-v1-apm-span-*`**
+ traceId - 트레이스의 고유 식별자입니다. 동일한 트레이스의 모든 범위는 동일한 traceId를 공유합니다.
+ spanId - 추적 내에 있는 범위의 고유 식별자로, 범위가 생성될 때 할당됩니다.
+ parentSpanId -이 범위의 상위 범위의 spanId입니다. 루트 범위인 경우 이 필드는 비어 있어야 합니다.
+ durationInNanos - startTime과 endTime 간의 나노초 차이입니다(UI에서 `latency`에 있음).
+ serviceName - 범위가 시작되는 리소스입니다.
+ traceGroup - 트레이스의 루트 범위 이름입니다.

**`otel-v1-apm-service-map`**
+ serviceName - 범위를 내보내는 서비스의 이름입니다.
+ destination.domain - 이 클라이언트가 호출하는 서비스의 serviceName입니다.
+ destination.resource - 이 클라이언트가 호출하는 범위 이름(API, 작업 등)입니다.
+ target.domain - 클라이언트가 호출하는 서비스의 serviceName입니다.
+ target.resource - 클라이언트가 호출하는 범위 이름(API, 작업 등)입니다.
+ traceGroupName - 요청 체인을 시작한 최상위 범위 이름입니다.

**요구 사항**  
**join**에서 다음을 계산하도록 지원합니다.

각 서비스에 대해 서비스 맵 인덱스의 범위 인덱스를 조인하여 다양한 유형의 필터에서 지표를 계산합니다.

이 샘플 쿼리는 `order` 서비스의 추적 그룹 `client_cancel_order`별로 필터링할 때 지연 시간을 계산합니다.

```
SELECT avg(durationInNanos)
FROM `otel-v1-apm-span-000001` t1
WHERE t1.serviceName = `order`
  AND ((t1.name in
          (SELECT target.resource
           FROM `otel-v1-apm-service-map`
           WHERE serviceName = `order`
             AND traceGroupName = `client_cancel_order`)
        AND t1.parentSpanId != NULL)
       OR (t1.parentSpanId = NULL
           AND t1.name = `client_cancel_order`))
  AND t1.traceId in
    (SELECT traceId
     FROM `otel-v1-apm-span-000001`
     WHERE serviceName = `order`)
```

**PPL로 마이그레이션**  
join 명령의 구문

```
SEARCH source=<left-table>
| <other piped command>
| [joinType] JOIN
    [leftAlias]
    ON joinCriteria
    <right-table>
| <other piped command>
```

**다시 작성**  


```
SEARCH source=otel-v1-apm-span-000001
| WHERE serviceName = 'order'
| JOIN left=t1 right=t2
    ON t1.traceId = t2.traceId AND t2.serviceName = 'order'
    otel-v1-apm-span-000001 -- self inner join
| EVAL s_name = t1.name -- rename to avoid ambiguous
| EVAL s_parentSpanId = t1.parentSpanId -- RENAME command would be better when it is supported
| EVAL s_durationInNanos = t1.durationInNanos 
| FIELDS s_name, s_parentSpanId, s_durationInNanos -- reduce colunms in join
| LEFT JOIN left=s1 right=t3
    ON s_name = t3.target.resource AND t3.serviceName = 'order' AND t3.traceGroupName = 'client_cancel_order'
    otel-v1-apm-service-map
| WHERE (s_parentSpanId IS NOT NULL OR (s_parentSpanId IS NULL AND s_name = 'client_cancel_order'))
| STATS avg(s_durationInNanos) -- no need to add alias if there is no ambiguous
```

**joinType**
+ 구문: `INNER | LEFT OUTER | CROSS`
+ 선택 사항
+ 수행할 조인의 유형입니다. 지정하지 않으면 기본값은 `INNER`입니다.

**leftAlias**
+ 구문: `left = <leftAlias>`
+ 선택 사항
+ 모호한 이름 지정을 방지하기 위해 왼쪽 조인 측에 사용할 하위 쿼리 별칭입니다.

**joinCriteria**
+ 구문: `<expression>`
+ 필수
+ 이 구문은 `ON`으로 시작합니다. 모든 비교 표현식일 수 있습니다. 일반적으로 조인 기준은 `<leftAlias>.<leftField>=<rightAlias>.<rightField>`와 같습니다.

  예를 들어 `l.id = r.id`입니다. 조인 기준에 여러 조건이 포함된 경우 각 비교 표현식 간에 `AND` 및 `OR` 연산자를 지정할 수 있습니다. 예를 들어 `l.id = r.id AND l.email = r.email AND (r.age > 65 OR r.age < 18)`입니다.

**추가 예제**  
SQL 쿼리에서 마이그레이션(TPC-H Q13):

```
SELECT c_count, COUNT(*) AS custdist
FROM
  ( SELECT c_custkey, COUNT(o_orderkey) c_count
    FROM customer LEFT OUTER JOIN orders ON c_custkey = o_custkey
        AND o_comment NOT LIKE '%unusual%packages%'
    GROUP BY c_custkey
  ) AS c_orders
GROUP BY c_count
ORDER BY custdist DESC, c_count DESC;
```

PPL 조인 쿼리로 다시 작성:

```
SEARCH source=customer
| FIELDS c_custkey
| LEFT OUTER JOIN
    ON c_custkey = o_custkey AND o_comment NOT LIKE '%unusual%packages%'
    orders
| STATS count(o_orderkey) AS c_count BY c_custkey
| STATS count() AS custdist BY c_count
| SORT - custdist, - c_count
```

제한: 오른쪽 조인에서는 하위 검색이 지원되지 않습니다.

하위 검색이 지원되는 경우 다음과 같이 위의 PPL 쿼리를 다시 작성할 수 있습니다.

```
SEARCH source=customer
| FIELDS c_custkey
| LEFT OUTER JOIN
   ON c_custkey = o_custkey
   [
      SEARCH source=orders
      | WHERE o_comment NOT LIKE '%unusual%packages%'
      | FIELDS o_orderkey, o_custkey
   ]
| STATS count(o_orderkey) AS c_count BY c_custkey
| STATS count() AS custdist BY c_count
| SORT - custdist, - c_count
```

#### lookup 명령
<a name="supported-ppl-lookup-commands"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`lookup` 명령을 사용하여 조회 인덱스(차원 테이블)의 데이터를 추가하거나 대체하여 검색 데이터를 보강합니다. 이 명령을 사용하면 인덱스의 필드를 차원 테이블의 값으로 확장할 수 있습니다. 조회 조건이 충족되면 이를 사용하여 값을 추가하거나 바꿀 수도 있습니다. 정적 데이터 세트로 소스 데이터를 보강하는 `Join` 명령보다 `lookup` 명령이 더 적합합니다.

**구문**  
다음 구문을 사용합니다.

```
SEARCH source=<sourceIndex>
| <other piped command>
| LOOKUP <lookupIndex> (<lookupMappingField> [AS <sourceMappingField>])...
    [(REPLACE | APPEND) (<inputField> [AS <outputField>])...]
| <other piped command>
```

**lookupIndex**
+ 필수 사항입니다.
+ 조회 인덱스의 이름(차원 테이블)입니다.

**lookupMappingField**
+ 필수 사항입니다.
+ 오른쪽 테이블의 조인 키와 유사한 조회 인덱스의 매핑 키입니다. 여러 필드를 쉼표로 구분하여 지정할 수 있습니다.

**sourceMappingField**
+ 선택 사항.
+ 기본값: <lookupMappingField>.
+ 소스 쿼리의 매핑 키로, 왼쪽의 조인 키와 유사합니다.

**inputField**
+ 선택 사항.
+ 기본값: 일치하는 값이 있는 조회 인덱스의 모든 필드입니다.
+ 일치하는 값이 결과 출력에 적용되는 조회 인덱스의 필드입니다. 여러 필드를 쉼표로 구분하여 지정할 수 있습니다.

**outputField**
+ 선택 사항.
+ 기본값: `<inputField>`.
+ 출력의 필드입니다. 여러 출력 필드를 지정할 수 있습니다. 소스 쿼리에서 기존 필드 이름을 지정하면 해당 값이 inputField의 일치하는 값으로 대체되거나 추가됩니다. 새 필드 이름을 지정하면 결과에 추가됩니다.

**REPLACE \$1 APPEND**
+ 선택 사항.
+ 기본값: REPLACE
+ 일치하는 값을 처리하는 방법을 지정합니다. REPLACE를 지정하면 <lookupIndex> 필드의 일치하는 값이 결과의 값을 덮어씁니다. `APPEND`를 지정하면 <lookupIndex> 필드의 일치하는 값이 결과에서 누락된 값에만 추가됩니다.

**사용법**
+ LOOKUP <lookupIndex> id AS cid REPLACE mail AS email
+ LOOKUP <lookupIndex> name REPLACE mail AS email
+ LOOKUP <lookupIndex> id AS cid, name APPEND address, mail AS email
+ LOOKUP <lookupIndex> id

**예제**  
다음 예시를 참조하세요.

```
SEARCH source=<sourceIndex>
| WHERE orderType = 'Cancelled'
| LOOKUP account_list, mkt_id AS mkt_code REPLACE amount, account_name AS name
| STATS count(mkt_code), avg(amount) BY name
```

```
SEARCH source=<sourceIndex>
| DEDUP market_id
| EVAL category=replace(category, "-", ".")
| EVAL category=ltrim(category, "dvp.")
| LOOKUP bounce_category category AS category APPEND classification
```

```
SEARCH source=<sourceIndex>
| LOOKUP bounce_category category
```

#### parse 명령
<a name="supported-ppl-parse-command"></a>

`parse` 명령은 정규식을 사용하여 텍스트 필드를 구문 분석하고 검색 결과에 결과를 추가합니다.

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

**구문**  
다음 구문을 사용합니다.

```
parse <field> <pattern>    
```

**`field`**
+ 필수.
+ 필드는 텍스트 필드여야 합니다.

**`pattern`**
+ 필수 문자열입니다.
+ 지정된 텍스트 필드에서 새 필드를 추출하는 데 사용되는 정규식 패턴입니다.
+ 새 필드 이름이 이미 사용 중인 경우 원래 필드를 대체합니다.

**정규식**  
정규식 패턴은 Java 정규식 엔진을 사용하여 각 문서의 전체 텍스트 필드를 매칭하는 데 사용됩니다. 표현식의 각 명명된 캡처 그룹은 새 `STRING` 필드가 됩니다.

**예 1: 새 필드 생성**  
이 예에서는 각 문서에 대해 새 필드 `host`를 생성하는 방법을 보여줍니다. `host`는 `email` 필드에서 `@` 뒤에 오는 호스트 이름이 됩니다. null 필드를 구문 분석하면 빈 문자열이 반환됩니다.

PPL 쿼리:

```
os> source=accounts | parse email '.+@(?<host>.+)' | fields email, host ;
fetched rows / total rows = 4/4
+-----------------------+-------------+
| email                 | host        |
|-----------------------+-------------|
| jane_doe@example.com  | example.com |
| john_doe@example.net  | example.net |
| null                  |             |
| juan_li@example.org   | example.org |
+-----------------------+-------------+
```

**예 2: 기존 필드 재정의**  
이 예에서는 번지가 제거된 기존 `address` 필드를 재정의하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | parse address '\d+ (?<address>.+)' | fields address ;
fetched rows / total rows = 4/4
+------------------+
| address          |
|------------------|
| Example Lane     |
| Example Street   |
| Example Avenue   |
| Example Court    |
+------------------+
```

**예 3: 캐스팅된 구문 분석된 필드를 기준으로 필터링 및 정렬**  
이 예는 `address` 필드에서 500보다 높은 번지를 정렬하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | parse address '(?<streetNumber>\d+) (?<street>.+)' | where cast(streetNumber as int) > 500 | sort num(streetNumber) | fields streetNumber, street ;
fetched rows / total rows = 3/3
+----------------+----------------+
| streetNumber   | street         |
|----------------+----------------|
| ***            | Example Street |
| ***            | Example Avenue |
| 880            | Example Lane   |
+----------------+----------------+
```

**제한 사항**  
parse 명령에는 몇 가지 제한 사항이 있습니다.
+ parse로 정의된 필드는 다시 구문 분석할 수 없습니다.

  다음 명령은 작동하지 않습니다.

  ```
  source=accounts | parse address '\d+ (?<street>.+)' | parse street '\w+ (?<road>\w+)'
  ```
+ parse로 정의된 필드는 다른 명령으로 재정의할 수 없습니다.

  `street`를 재정의할 수 없으므로 `where`는 문서와 매칭되지 않습니다.

  ```
  source=accounts | parse address '\d+ (?<street>.+)' | eval street='1' | where street='1' ;        
  ```
+ parse에 사용되는 텍스트 필드는 재정의할 수 없습니다.

  `address`가 재정의되므로 `street`는 성공적으로 구문 분석되지 않습니다.

  ```
  source=accounts | parse address '\d+ (?<street>.+)' | eval address='1' ;        
  ```
+ parse로 정의된 필드는 `stats` 명령에서 사용한 후 필터링하거나 정렬할 수 없습니다.

  다음 명령의 `where`는 작동하지 않습니다.

  ```
  source=accounts | parse email '.+@(?<host>.+)' | stats avg(age) by host | where host=pyrami.com ;        
  ```

#### patterns 명령
<a name="supported-ppl-patterns-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`patterns` 명령은 텍스트 필드에서 로그 패턴을 추출하고 그 결과를 검색 결과에 추가합니다. 로그를 패턴별로 그룹화하면 분석 및 문제 해결을 위해 대량의 로그 데이터에서 통계를 더 쉽게 집계할 수 있습니다.

**구문**  
다음 구문을 사용합니다.

```
patterns [new_field=<new-field-name>] [pattern=<pattern>] <field>    
```

**new-field-name**
+ 선택 사항인 문자열입니다.
+ 추출된 패턴에 해당하는 새 필드의 이름입니다.
+ 기본값은 `patterns_field`입니다.
+ 해당 이름이 이미 사용 중인 경우 원래 필드를 대체합니다.

**pattern**
+ 선택 사항인 문자열입니다.
+ 텍스트 필드에서 필터링해야 하는 정규식 문자 패턴입니다.
+ 없는 경우 기본 패턴은 영숫자 문자(`[a-zA-Z\d]`)입니다.

**필드**
+ 필수.
+ 필드는 텍스트 필드여야 합니다.

**예 1: 새 필드 생성**  
이 예에서는 각 문서에 대해 `email`에서 추출 구두점을 사용하는 방법을 보여줍니다. null 필드를 구문 분석하면 빈 문자열이 반환됩니다.

PPL 쿼리:

```
os> source=accounts | patterns email | fields email, patterns_field ;
fetched rows / total rows = 4/4
+-----------------------+------------------+
| email                 | patterns_field   |
|-----------------------+------------------|
| jane_doe@example.com  | @.               |
| john_doe@example.net  | @.               |
| null                  |                  |
| juan_li@example.org   | @.               |
+-----------------------+------------------+
```

**예 2: 로그 패턴 추출**  
이 예에서는 기본 패턴을 사용하여 원시 로그 필드에서 구두점을 추출하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=apache | patterns message | fields message, patterns_field ;
fetched rows / total rows = 4/4
+-----------------------------------------------------------------------------------------------------------------------------+---------------------------------+
| message                                                                                                                     | patterns_field                  |
|-----------------------------------------------------------------------------------------------------------------------------+---------------------------------|
| 177.95.8.74 - upton5450 [28/Sep/2022:10:15:57 -0700] "HEAD /e-business/mindshare HTTP/1.0" 404 19927                        | ... -  [//::: -] " /-/ /."      |
| ************ - pouros8756 [28/Sep/2022:10:15:57 -0700] "GET /architectures/convergence/niches/mindshare HTTP/1.0" 100 28722 | ... -  [//::: -] " //// /."     |
| *************** - - [28/Sep/2022:10:15:57 -0700] "PATCH /strategize/out-of-the-box HTTP/1.0" 401 27439                      | ... - - [//::: -] " //--- /."   |
| ************** - - [28/Sep/2022:10:15:57 -0700] "POST /users HTTP/1.1" 301 9481                                             | ... - - [//::: -] " / /."       |
+-----------------------------------------------------------------------------------------------------------------------------+---------------------------------+
```

**예 3: 사용자 지정 정규식 패턴을 사용하여 로그 패턴 추출**  
이 예에서는 사용자 정의 패턴을 사용하여 원시 로그 필드에서 구두점을 추출하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=apache | patterns new_field='no_numbers' pattern='[0-9]' message | fields message, no_numbers ;
fetched rows / total rows = 4/4
+-----------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------+
| message                                                                                                                     | no_numbers                                                                           |
|-----------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------|
| 177.95.8.74 - upton5450 [28/Sep/2022:10:15:57 -0700] "HEAD /e-business/mindshare HTTP/1.0" 404 19927                        | ... - upton [/Sep/::: -] "HEAD /e-business/mindshare HTTP/."                         |
| 127.45.152.6 - pouros8756 [28/Sep/2022:10:15:57 -0700] "GET /architectures/convergence/niches/mindshare HTTP/1.0" 100 28722 | ... - pouros [/Sep/::: -] "GET /architectures/convergence/niches/mindshare HTTP/."   |
| *************** - - [28/Sep/2022:10:15:57 -0700] "PATCH /strategize/out-of-the-box HTTP/1.0" 401 27439                      | ... - - [/Sep/::: -] "PATCH /strategize/out-of-the-box HTTP/."                       |
| ************** - - [28/Sep/2022:10:15:57 -0700] "POST /users HTTP/1.1" 301 9481                                             | ... - - [/Sep/::: -] "POST /users HTTP/."                                            |
+-----------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------+
```

**제한 사항**  
patterns 명령에는 구문 분석 명령과 동일한 제한 사항이 있습니다.

#### rare 명령
<a name="supported-ppl-rare-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`rare` 명령을 사용하여 필드 목록에서 모든 필드 값의 가장 덜 흔한 튜플을 찾습니다.

**참고**  
그룹별 필드의 개별 값 튜플마다 최대 10개의 결과가 반환됩니다.

**구문**  
다음 구문을 사용합니다.

```
rare [N] <field-list> [by-clause] rare_approx [N] <field-list> [by-clause]
```

**field-list**
+ 필수.
+ 쉼표로 구분된 필드 이름의 목록입니다.

**by-clause**
+ 선택 사항.
+ 결과를 그룹화할 하나 이상의 필드입니다.

**N**
+ 반환할 결과 수.
+ 기본값: 10

**rare\$1approx**
+ [HyperLogLog\$1\$1 알고리즘의 예상 카디널리티](https://spark.apache.org/docs/latest/sql-ref-functions-builtin.html)를 사용하여 드문(n) 필드의 개수를 근사값으로 계산합니다.

**예 1: 필드에서 가장 덜 흔한 값 찾기**  
이 예에서는 모든 계정의 가장 덜 흔한 성별을 찾습니다.

PPL 쿼리:

```
os> source=accounts | rare gender;
os> source=accounts | rare_approx 10 gender;
os> source=accounts | rare_approx gender;
fetched rows / total rows = 2/2
+----------+
| gender   |
|----------|
| F        |
| M        |
+----------+
```

**예 2: 성별별로 구성된 가장 덜 흔한 값 찾기**  
이 예에서는 성별을 기준으로 모든 계정 그룹의 가장 덜 흔한 연령을 찾습니다.

PPL 쿼리:

```
os> source=accounts | rare 5 age by gender;
os> source=accounts | rare_approx 5 age by gender;
fetched rows / total rows = 4/4
+----------+-------+
| gender   | age   |
|----------+-------|
| F        | 28    |
| M        | 32    |
| M        | 33    |
| M        | 36    |
+----------+-------+
```

#### rename 명령
<a name="supported-ppl-rename-command"></a>

`rename` 명령을 사용하여 검색 결과에서 하나 이상의 필드 이름을 변경합니다.

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

**구문**  
다음 구문을 사용합니다.

```
rename <source-field> AS <target-field>["," <source-field> AS <target-field>]...    
```

**source-field**
+ 필수.
+ 이름을 바꾸려는 필드의 이름입니다.

**target-field**
+ 필수.
+ 바꾸려는 이름입니다.

**예 1: 단일 필드 이름 바꾸기**  
이 예에서는 단일 필드의 이름을 바꾸는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | rename account_number as an | fields an;
fetched rows / total rows = 4/4
+------+
| an   |
|------|
| 1    |
| 6    |
| 13   |
| 18   |
+------+
```

**예 2: 여러 필드 이름 바꾸기**  
이 예에서는 여러 필드의 이름을 바꾸는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | rename account_number as an, employer as emp | fields an, emp;
fetched rows / total rows = 4/4
+------+---------+
| an   | emp     |
|------+---------|
| 1    | Pyrami  |
| 6    | Netagy  |
| 13   | Quility |
| 18   | null    |
+------+---------+
```

**제한 사항**
+ 기존 필드 재정의는 지원되지 않습니다.

  ```
  source=accounts | grok address '%{NUMBER} %{GREEDYDATA:address}' | fields address        
  ```

#### search 명령
<a name="supported-ppl-search-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`search` 명령을 사용하여 인덱스에서 문서를 검색합니다. `search` 명령은 PPL 쿼리에서 첫 번째 명령으로만 사용할 수 있습니다.

**구문**  
다음 구문을 사용합니다.

```
search source=[<remote-cluster>:]<index> [boolean-expression]    
```

**검색**
+ 선택 사항.
+ 생략할 수 있는 검색 키워드입니다.

**인덱스**
+ 필수.
+ search 명령은 쿼리할 인덱스를 지정해야 합니다.
+ 클러스터 간 검색을 위해 `<cluster name>:`이 인덱스 이름 앞에 접두사를 붙일 수 있습니다.

**bool-expression**
+ 선택 사항.
+ 부울 값으로 평가되어야 하는 표현식 문자열입니다.

**예 1: 모든 데이터 가져오기**  
이 예는 계정 인덱스에서 모든 문서를 가져오는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts;
+------------------+-------------+----------------------+-----------+----------+--------+----------------+---------+-------+-----------------------+------------+
| account_number   | firstname   | address              | balance   | gender   | city   | employer       | state   | age   | email                 | lastname   |
|------------------+-------------+----------------------+-----------+----------+--------+----------------+---------+-------+-----------------------+------------|
| 1                | Jorge       | *** Any Lane         | 39225     | M        | Brogan | ExampleCorp    | IL      | 32    | jane_doe@example.com  | Souza      |
| 6                | John        | *** Example Street   | 5686      | M        | Dante  | AnyCorp        | TN      | 36    | john_doe@example.com  | Doe        |
| 13               | Jane        | *** Any Street       | *****     | F        | Nogal  | ExampleCompany | VA      | 28    | null                  | Doe        |
| 18               | Juan        | *** Example Court    | 4180      | M        | Orick  | null           | MD      | 33    | juan_li@example.org   | Li         |
+------------------+-------------+----------------------+-----------+----------+--------+----------------+---------+-------+-----------------------+------------+
```

**예 2: 조건을 사용하여 데이터 가져오기**  
이 예는 계정 인덱스에서 모든 문서를 가져오는 방법을 보여줍니다.

PPL 쿼리:

```
os> SEARCH source=accounts account_number=1 or gender="F";
+------------------+-------------+--------------------+-----------+----------+--------+----------------+---------+-------+-------------------------+------------+
| account_number   | firstname   | address            | balance   | gender   | city   | employer       | state   | age   | email                -  | lastname   |
|------------------+-------------+--------------------+-----------+----------+--------+----------------+---------+-------+-------------------------+------------|
| 1                | Jorge       | *** Any Lane       | *****     | M        | Brogan | ExampleCorp    | IL      | 32    | jorge_souza@example.com | Souza      |
| 13               | Jane        | *** Any Street     | *****     | F        | Nogal  | ExampleCompany | VA      | 28    | null                    | Doe        |
+------------------+-------------+--------------------+-----------+----------+--------+-----------------+---------+-------+------------------------+------------+
```

#### sort 명령
<a name="supported-ppl-sort-command"></a>

`sort` 명령을 사용하여 지정된 필드를 기준으로 검색 결과를 정렬합니다.

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

**구문**  
다음 구문을 사용합니다.

```
sort <[+|-] sort-field>...
```

**[\$1\$1-]**
+ 선택 사항.
+ 더하기[\$1]는 NULL/MISSING 값이 맨 처음에 오는 오름차순을 나타냅니다.
+ 빼기[-]는 NULL/MISSING 값이 마지막에 오는 내림차순을 나타냅니다.
+ 기본값: NULL/MISSING 값이 맨 처음에 오는 오름차순입니다.

**sort-field**
+ 필수.
+ 정렬에 사용되는 필드입니다.

**예 1: 단일 필드로 정렬**  
이 예에서는 연령 필드를 사용하여 문서를 오름차순으로 정렬하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | sort age | fields account_number, age;
fetched rows / total rows = 4/4
+------------------+-------+
| account_number   | age   |
|------------------+-------|
| 13               | 28    |
| 1                | 32    |
| 18               | 33    |
| 6                | 36    |
+------------------+-------+
```

**예 2: 단일 필드로 정렬하고 모든 결과를 반환**  
이 예에서는 연령 필드를 사용하여 문서를 오름차순으로 정렬하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | sort age | fields account_number, age;
fetched rows / total rows = 4/4
+------------------+-------+
| account_number   | age   |
|------------------+-------|
| 13               | 28    |
| 1                | 32    |
| 18               | 33    |
| 6                | 36    |
+------------------+-------+
```

**예 3: 단일 필드를 기준으로 내림차순으로 정렬**  
이 예에서는 연령 필드를 사용하여 문서를 내림차순으로 정렬하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | sort - age | fields account_number, age;
fetched rows / total rows = 4/4
+------------------+-------+
| account_number   | age   |
|------------------+-------|
| 6                | 36    |
| 18               | 33    |
| 1                | 32    |
| 13               | 28    |
+------------------+-------+
```

**예 4: 여러 필드를 기준으로 정렬**  
이 예에서는 성별 필드를 오름차순으로 정렬하고 연령 필드를 내림차순으로 정렬하는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | sort + gender, - age | fields account_number, gender, age;
fetched rows / total rows = 4/4
+------------------+----------+-------+
| account_number   | gender   | age   |
|------------------+----------+-------|
| 13               | F        | 28    |
| 6                | M        | 36    |
| 18               | M        | 33    |
| 1                | M        | 32    |
+------------------+----------+-------+
```

**예 5: 정렬 기준 필드에 null 값 포함**  
이 예에서는 기본 옵션(오름차순 및 null 우선)을 기준으로 고용주 필드를 정렬하는 방법을 보여줍니다. 결과를 보면 null 값이 첫 번째 행에 있는 것을 확인할 수 있습니다.

PPL 쿼리:

```
os> source=accounts | sort employer | fields employer;
fetched rows / total rows = 4/4
+------------+
| employer   |
|------------|
| null       |
| AnyCompany |
| AnyCorp    |
| AnyOrgty   |
+------------+
```

#### stats 명령
<a name="supported-ppl-stats-command"></a>

`stats` 명령을 사용하여 검색 결과에서 집계를 계산합니다.

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

**NULL/MISSING 값 처리**  



**NULL/MISSING 값 처리**  

| 함수 | NULL | MISSING | 
| --- | --- | --- | 
| COUNT | 계산되지 않음 | 계산되지 않음 | 
| SUM | 무시 | 무시 | 
| AVG | 무시 | 무시 | 
| MAX | 무시 | 무시 | 
| MIN | 무시 | 무시 | 

**구문**  
다음 구문을 사용합니다.

```
stats <aggregation>... [by-clause]    
```

**aggregation**
+ 필수.
+ 필드에 적용되는 집계 함수입니다.

**by-clause**
+ 선택 사항.
+ 구문: `by [span-expression,] [field,]...`
+ 집계 결과를 그룹화하기 위한 필드와 표현식을 지정합니다. by-clause는 필드와 표현식을 사용하여 집계 결과를 그룹화할 수 있도록 합니다. 스칼라 함수, 집계 함수 및 범위 표현식을 사용하여 특정 필드를 동일한 간격의 버킷으로 분할할 수 있습니다.
+ 기본값: `<by-clause>`를 지정하지 않으면 stats 명령은 전체 결과 집합에 대한 집계를 나타내는 단일 행을 반환합니다.

**span 표현식**  

+ 선택 사항, 최대 1개.
+ 구문: `span(field_expr, interval_expr)`
+ interval 표현식의 단위는 기본적으로 자연 단위입니다. 필드가 날짜 및 시간 유형 필드이고 간격이 날짜/시간 단위인 경우, 간격 표현식에 단위를 지정합니다.
+ 예를 들어 `age` 필드를 10년 단위의 버킷으로 분할하면 `span(age, 10)`과 비슷하게 보입니다. 타임스탬프 필드를 1시간 간격으로 분할하려면 `span(timestamp, 1h)`을 사용합니다.


**사용 가능한 시간 단위**  

| 범위 간격 단위 | 
| --- | 
| 밀리초(ms) | 
| 초(초) | 
| 분(m, 대소문자 구분) | 
| 시간(h) | 
| 일(d) | 
| 주(w) | 
| 월(M, 대소문자 구분) | 
| 분기(q) | 
| 년(y) | 

**집계 함수**  


**`COUNT`**  
SELECT 문으로 검색된 행의 expr 수를 반환합니다.

예제:

```
os> source=accounts | stats count();
fetched rows / total rows = 1/1
+-----------+
| count()   |
|-----------|
| 4         |
+-----------+
```

**`SUM`**  
`SUM(expr)`을 사용하여 expr의 합계를 반환합니다.

예제

```
os> source=accounts | stats sum(age) by gender;
fetched rows / total rows = 2/2
+------------+----------+
| sum(age)   | gender   |
|------------+----------|
| 28         | F        |
| 101        | M        |
+------------+----------+
```

**`AVG`**  
`AVG(expr)`를 사용하여 expr의 평균 값을 반환합니다.

예제

```
os> source=accounts | stats avg(age) by gender;
fetched rows / total rows = 2/2
+--------------------+----------+
| avg(age)           | gender   |
|--------------------+----------|
| 28.0               | F        |
| 33.666666666666664 | M        |
+--------------------+----------+
```

**`MAX`**  
`MAX(expr)`를 사용하여 expr의 최대값을 반환합니다.

예제

```
os> source=accounts | stats max(age);
fetched rows / total rows = 1/1
+------------+
| max(age)   |
|------------|
| 36         |
+------------+
```

**`MIN`**  
`MIN(expr)`을 사용하여 expr의 최소값을 반환합니다.

예제

```
os> source=accounts | stats min(age);
fetched rows / total rows = 1/1
+------------+
| min(age)   |
|------------|
| 28         |
+------------+
```

**`STDDEV_SAMP`**  
`STDDEV_SAMP(expr)`를 사용하여 expr의 샘플 표준 편차를 반환합니다.

예제:

```
os> source=accounts | stats stddev_samp(age);
fetched rows / total rows = 1/1
+--------------------+
| stddev_samp(age)   |
|--------------------|
| 3.304037933599835  |
+--------------------+
```

**STDDEV\$1POP**  
`STDDEV_POP(expr)`를 사용하여 expr의 모집단 표준 편차를 반환합니다.

예제:

```
os> source=accounts | stats stddev_pop(age);
fetched rows / total rows = 1/1
+--------------------+
| stddev_pop(age)    |
|--------------------|
| 2.**************** |
+--------------------+
```

**TAKE**  
`TAKE(field [, size])`를 사용하여 필드의 원래 값을 반환합니다. 값의 순서를 보장하지는 않습니다.

**필드**
+ 필수.
+ 필드는 텍스트 필드여야 합니다.

**size**
+ 선택 사항인 정수입니다.
+ 값 수를 반환해야 합니다.
+ 기본값은 10입니다.

**예제**  


```
os> source=accounts | stats take(firstname);
fetched rows / total rows = 1/1
+-----------------------------+
| take(firstname)             |
|-----------------------------|
| [Jane, Mary, Nikki, Juan    |
+-----------------------------+
```

**PERCENTILE 또는 PERCENTILE\$1APPROX**  
`PERCENTILE(expr, percent)` 또는 `PERCENTILE_APPROX(expr, percent)`를 사용하여 expr의 대략적인 백분위수 값을 지정된 백분율로 반환합니다.

**%**
+ 숫자는 0에서 100 사이의 상수여야 합니다.

**예제**  


```
os> source=accounts | stats percentile(age, 90) by gender;
fetched rows / total rows = 2/2
+-----------------------+----------+
| percentile(age, 90)   | gender   |
|-----------------------+----------|
| 28                    | F        |
| 36                    | M        |
+-----------------------+----------+
```

**예 1: 이벤트 수 계산**  
이 예는 계정의 이벤트 수를 계산하는 방법을 보여줍니다.

```
os> source=accounts | stats count();
fetched rows / total rows = 1/1
+-----------+
| count()   |
|-----------|
| 4         |
+-----------+
```

**예 2: 필드의 평균 계산**  
이 예에서는 모든 계정의 평균 연령을 계산하는 방법을 보여줍니다.

```
os> source=accounts | stats avg(age);
fetched rows / total rows = 1/1
+------------+
| avg(age)   |
|------------|
| 32.25      |
+------------+
```

**예 3: 그룹별 필드 평균 계산**  
이 예는 성별별로 그룹화된 모든 계정의 평균 연령을 계산하는 방법을 보여줍니다.

```
os> source=accounts | stats avg(age) by gender;
fetched rows / total rows = 2/2
+--------------------+----------+
| avg(age)           | gender   |
|--------------------+----------|
| 28.0               | F        |
| 33.666666666666664 | M        |
+--------------------+----------+
```

**예 4: 그룹별 필드의 평균, 합계 및 개수 계산**  
이 예에서는 성별별로 그룹화된 모든 계정의 평균 연령, 합계 연령 및 이벤트 수를 계산하는 방법을 보여줍니다.

```
os> source=accounts | stats avg(age), sum(age), count() by gender;
fetched rows / total rows = 2/2
+--------------------+------------+-----------+----------+
| avg(age)           | sum(age)   | count()   | gender   |
|--------------------+------------+-----------+----------|
| 28.0               | 28         | 1         | F        |
| 33.666666666666664 | 101        | 3         | M        |
+--------------------+------------+-----------+----------+
```

**예 5: 필드의 최대값 계산**  
이 예에서는 모든 계정의 최대 연령을 계산합니다.

```
os> source=accounts | stats max(age);
fetched rows / total rows = 1/1
+------------+
| max(age)   |
|------------|
| 36         |
+------------+
```

**예 6: 그룹별 필드의 최대값 및 최소값 계산**  
이 예에서는 성별별로 그룹화된 모든 계정의 최대 및 최소 연령 값을 계산합니다.

```
os> source=accounts | stats max(age), min(age) by gender;
fetched rows / total rows = 2/2
+------------+------------+----------+
| max(age)   | min(age)   | gender   |
|------------+------------+----------|
| 28         | 28         | F        |
| 36         | 32         | M        |
+------------+------------+----------+
```

**예 7: 필드의 고유 개수 계산**  
필드의 고유 값 수를 가져오려면 `COUNT` 대신 `DISTINCT_COUNT`(또는 `DC`) 함수를 사용할 수 있습니다. 이 예에서는 모든 계정의 성별 필드 수와 고유 수를 모두 계산합니다.

```
os> source=accounts | stats count(gender), distinct_count(gender);
fetched rows / total rows = 1/1
+-----------------+--------------------------+
| count(gender)   | distinct_count(gender)   |
|-----------------+--------------------------|
| 4               | 2                        |
+-----------------+--------------------------+
```

**예 8: 범위별로 개수 계산**  
이 예에서는 연령을 10년 간격으로 가져옵니다.

```
os> source=accounts | stats count(age) by span(age, 10) as age_span
fetched rows / total rows = 2/2
+--------------+------------+
| count(age)   | age_span   |
|--------------+------------|
| 1            | 20         |
| 3            | 30         |
+--------------+------------+
```

**예 9: 성별 및 범위별로 개수 계산**  
이 예에서는 5년의 성별 및 연령 범위별로 그룹화된 레코드를 계산합니다.

```
os> source=accounts | stats count() as cnt by span(age, 5) as age_span, gender
fetched rows / total rows = 3/3
+-------+------------+----------+
| cnt   | age_span   | gender   |
|-------+------------+----------|
| 1     | 25         | F        |
| 2     | 30         | M        |
| 1     | 35         | M        |
+-------+------------+----------+
```

범위 표현식은 명령에 지정된 순서에 관계없이 항상 첫 번째 그룹화 키로 표시됩니다.

```
os> source=accounts | stats count() as cnt by gender, span(age, 5) as age_span
fetched rows / total rows = 3/3
+-------+------------+----------+
| cnt   | age_span   | gender   |
|-------+------------+----------|
| 1     | 25         | F        |
| 2     | 30         | M        |
| 1     | 35         | M        |
+-------+------------+----------+
```

**예 10: 성별 및 범위별로 개수 계산 및 이메일 목록 가져오기**  
이 예에서는 10년 간격으로 연령을 구하고 성별별로 그룹을 구합니다. 또한 각 행에 대해 최대 5개의 이메일 목록을 가져옵니다.

```
os> source=accounts | stats count() as cnt, take(email, 5) by span(age, 5) as age_span, gender
fetched rows / total rows = 3/3
+-------+----------------------------------------------------+------------+----------+
| cnt   | take(email, 5)                                     | age_span   | gender   |
|-------+----------------------------------------------------+------------+----------|
| 1     | []                                                 | 25         | F        |
| 2     | [janedoe@anycompany.com,juanli@examplecompany.org] | 30         | M        |
| 1     | [marymajor@examplecorp.com]                        | 35         | M        |
+-------+----------------------------------------------------+------------+----------+
```

**예 11: 필드의 백분위수 계산**  
이 예에서는 모든 계정의 90세 백분위수를 계산하는 방법을 보여줍니다.

```
os> source=accounts | stats percentile(age, 90);
fetched rows / total rows = 1/1
+-----------------------+
| percentile(age, 90)   |
|-----------------------|
| 36                    |
+-----------------------+
```

**예 12: 그룹별로 필드의 백분위수 계산**  
이 예에서는 성별을 기준으로 모든 계정 그룹의 90세 백분위수를 계산하는 방법을 보여줍니다.

```
os> source=accounts | stats percentile(age, 90) by gender;
fetched rows / total rows = 2/2
+-----------------------+----------+
| percentile(age, 90)   | gender   |
|-----------------------+----------|
| 28                    | F        |
| 36                    | M        |
+-----------------------+----------+
```

**예 13: 성별 및 범위별로 백분위수 계산**  
이 예에서는 10년 간격으로 90세 백분위수를 구하고 성별로 그룹화합니다.

```
os> source=accounts | stats percentile(age, 90) as p90 by span(age, 10) as age_span, gender
fetched rows / total rows = 2/2
+-------+------------+----------+
| p90   | age_span   | gender   |
|-------+------------+----------|
| 28    | 20         | F        |
| 36    | 30         | M        |
+-------+------------+----------+
```

```
- `source = table | stats avg(a) `
- `source = table | where a < 50 | stats avg(c) `
- `source = table | stats max(c) by b`
- `source = table | stats count(c) by b | head 5`
- `source = table | stats distinct_count(c)`
- `source = table | stats stddev_samp(c)`
- `source = table | stats stddev_pop(c)`
- `source = table | stats percentile(c, 90)`
- `source = table | stats percentile_approx(c, 99)`
```

**범위를 사용한 집계**  


```
- `source = table  | stats count(a) by span(a, 10) as a_span`
- `source = table  | stats sum(age) by span(age, 5) as age_span | head 2`
- `source = table  | stats avg(age) by span(age, 20) as age_span, country  | sort - age_span |  head 2`
```

**기간 범위를 사용한 집계(텀블 윈도우 함수)**  


```
- `source = table | stats sum(productsAmount) by span(transactionDate, 1d) as age_date | sort age_date`
- `source = table | stats sum(productsAmount) by span(transactionDate, 1w) as age_date, productId`
```

**여러 수준별 집계 그룹**  


```
- `source = table | stats avg(age) as avg_state_age by country, state | stats avg(avg_state_age) as avg_country_age by country`
- `source = table | stats avg(age) as avg_city_age by country, state, city | eval new_avg_city_age = avg_city_age - 1 | stats avg(new_avg_city_age) as avg_state_age by country, state | where avg_state_age > 18 | stats avg(avg_state_age) as avg_adult_country_age by country`
```

#### subquery 명령
<a name="supported-ppl-subquery-commands"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`subquery` 명령을 사용하여 파이프 처리 언어(PPL) 문 내에서 복잡한 중첩 쿼리를 수행합니다.

```
source=logs | where field in [ subquery source=events | where condition | fields field ]
```

이 예에서 기본 검색(`source=logs`)은 하위 쿼리(`source=events`)의 결과를 기준으로 필터링됩니다.

subquery 명령은 복잡한 데이터 분석을 위해 여러 수준의 중첩을 지원합니다.

**중첩 하위 쿼리 예**  


```
source=logs | where id in [ subquery source=users | where user in [ subquery source=actions | where action="login" | fields user] | fields uid ]  
```

**InSubquery 사용**
+ `source = outer | where a in [ source = inner | fields b ]`
+ `source = outer | where (a) in [ source = inner | fields b ]`
+ `source = outer | where (a,b,c) in [ source = inner | fields d,e,f ]`
+ `source = outer | where a not in [ source = inner | fields b ]`
+ `source = outer | where (a) not in [ source = inner | fields b ]`
+ `source = outer | where (a,b,c) not in [ source = inner | fields d,e,f ]`
+ `source = outer a in [ source = inner | fields b ]`(subquery로 필터링 검색)
+ `source = outer a not in [ source = inner | fields b ]`(subquery로 필터링 검색)
+ `source = outer | where a in [ source = inner1 | where b not in [ source = inner2 | fields c ] | fields b ]`(중첩)
+ `source = table1 | inner join left = l right = r on l.a = r.a AND r.a in [ source = inner | fields d ] | fields l.a, r.a, b, c`(조인 필터로)

**IN-Subquery PPL을 사용한 SQL 마이그레이션 예**  
TPC-H Q4(집계를 사용한 하위 쿼리)

```
select
  o_orderpriority,
  count(*) as order_count
from
  orders
where
  o_orderdate >= date '1993-07-01'
  and o_orderdate < date '1993-07-01' + interval '3' month
  and o_orderkey in (
    select
      l_orderkey
    from
      lineitem
    where l_commitdate < l_receiptdate
  )
group by
  o_orderpriority
order by
  o_orderpriority
```

PPL InSubquery 쿼리로 다시 작성:

```
source = orders
| where o_orderdate >= "1993-07-01" and o_orderdate < "1993-10-01" and o_orderkey IN
  [ source = lineitem
    | where l_commitdate < l_receiptdate
    | fields l_orderkey
  ]
| stats count(1) as order_count by o_orderpriority
| sort o_orderpriority
| fields o_orderpriority, order_count
```

TPC-H Q20(하위 쿼리에 중첩됨)

```
select
  s_name,
  s_address
from
  supplier,
  nation
where
  s_suppkey in (
    select
      ps_suppkey
    from
      partsupp
    where
      ps_partkey in (
        select
          p_partkey
        from
          part
        where
          p_name like 'forest%'
      )
  )
  and s_nationkey = n_nationkey
  and n_name = 'CANADA'
order by
  s_name
```

PPL InSubquery 쿼리로 다시 작성:

```
source = supplier
| where s_suppkey IN [
    source = partsupp
    | where ps_partkey IN [
        source = part
        | where like(p_name, "forest%")
        | fields p_partkey
      ]
    | fields ps_suppkey
  ]
| inner join left=l right=r on s_nationkey = n_nationkey and n_name = 'CANADA'
  nation
| sort s_name
```

**ExistsSubquery 사용**  
가정: `a`, `b`는 테이블 외부의 필드, `c`, `d`는 테이블 내부의 필드, `e`, `f`는 테이블 내부2의 필드입니다.
+ `source = outer | where exists [ source = inner | where a = c ]`
+ `source = outer | where not exists [ source = inner | where a = c ]`
+ `source = outer | where exists [ source = inner | where a = c and b = d ]`
+ `source = outer | where not exists [ source = inner | where a = c and b = d ]`
+ `source = outer exists [ source = inner | where a = c ]`(subquery로 필터링 검색)
+ `source = outer not exists [ source = inner | where a = c ]`(subquery로 필터링 검색)
+ `source = table as t1 exists [ source = table as t2 | where t1.a = t2.a ]`(테이블 별칭은 기존 하위 쿼리에서 유용함)
+ `source = outer | where exists [ source = inner1 | where a = c and exists [ source = inner2 | where c = e ] ]`(중첩)
+ `source = outer | where exists [ source = inner1 | where a = c | where exists [ source = inner2 | where c = e ] ]`(중첩)
+ `source = outer | where exists [ source = inner | where c > 10 ]`(상관 관계가 없는 exists)
+ `source = outer | where not exists [ source = inner | where c > 10 ]`(상관 관계가 없는 exists)
+ `source = outer | where exists [ source = inner ] | eval l = "nonEmpty" | fields l`(특별한 형태의 상관 관계가 없는 exists)

**ScalarSubquery 사용**  
가정: `a`, `b`는 테이블 외부의 필드, `c`, `d`는 테이블 내부의 필드, `e`, `f`는 중첩 테이블의 필드입니다.

**상관 관계가 없는 스칼라 하위 쿼리**  
Select에서:
+ `source = outer | eval m = [ source = inner | stats max(c) ] | fields m, a`
+ `source = outer | eval m = [ source = inner | stats max(c) ] + b | fields m, a`

Where에서:
+ `source = outer | where a > [ source = inner | stats min(c) ] | fields a`

Search 필터에서:
+ `source = outer a > [ source = inner | stats min(c) ] | fields a`

**상관관계가 있는 스칼라 하위 쿼리**  
Select에서:
+ `source = outer | eval m = [ source = inner | where outer.b = inner.d | stats max(c) ] | fields m, a`
+ `source = outer | eval m = [ source = inner | where b = d | stats max(c) ] | fields m, a`
+ `source = outer | eval m = [ source = inner | where outer.b > inner.d | stats max(c) ] | fields m, a`

Where에서:
+ `source = outer | where a = [ source = inner | where outer.b = inner.d | stats max(c) ]`
+ `source = outer | where a = [ source = inner | where b = d | stats max(c) ]`
+ `source = outer | where [ source = inner | where outer.b = inner.d OR inner.d = 1 | stats count() ] > 0 | fields a`

Search 필터에서:
+ `source = outer a = [ source = inner | where b = d | stats max(c) ]`
+ `source = outer [ source = inner | where outer.b = inner.d OR inner.d = 1 | stats count() ] > 0 | fields a`

**중첩된 스칼라 하위 쿼리**  

+ `source = outer | where a = [ source = inner | stats max(c) | sort c ] OR b = [ source = inner | where c = 1 | stats min(d) | sort d ]`
+ `source = outer | where a = [ source = inner | where c = [ source = nested | stats max(e) by f | sort f ] | stats max(d) by c | sort c | head 1 ]`

**(관계) 하위 쿼리**  
`InSubquery`, `ExistsSubquery` 및 `ScalarSubquery`는 모두 하위 쿼리 표현식입니다. 하지만 `RelationSubquery`는 하위 쿼리 표현식이 아니며 Join 또는 From 절에서 일반적으로 사용되는 하위 쿼리 계획입니다.
+ `source = table1 | join left = l right = r [ source = table2 | where d > 10 | head 5 ]`(오른쪽 조인의 하위 쿼리)
+ `source = [ source = table1 | join left = l right = r [ source = table2 | where d > 10 | head 5 ] | stats count(a) by b ] as outer | head 1`

**추가 컨텍스트**  
`InSubquery`, `ExistsSubquery` 및 `ScalarSubquery`는 `where` 절 및 검색 필터에 일반적으로 사용되는 하위 쿼리 표현식입니다.

Where 명령:

```
| where <boolean expression> | ...    
```

Search 필터

```
search source=* <boolean expression> | ...    
```

하위 쿼리 표현식은 부울 표현식에 사용할 수 있습니다.

```
| where orders.order_id in [ source=returns | where return_reason="damaged" | field order_id ]    
```

`orders.order_id in [ source=... ]`는 `<boolean expression>`입니다.

일반적으로 이러한 종류의 하위 쿼리 절에는 `InSubquery` 표현식이라는 이름이 지정됩니다. `<boolean expression>`입니다.

**조인 유형이 다른 하위 쿼리**  
`ScalarSubquery`를 사용하는 예:

```
source=employees
| join source=sales on employees.employee_id = sales.employee_id
| where sales.sale_amount > [ source=targets | where target_met="true" | fields target_value ]
```

InSubquery, ExistsSubquery 및 ScalarSubquery와 달리 RelationSubquery는 하위 쿼리 표현식이 아니라, 하위 쿼리 계획입니다.

```
SEARCH source=customer
| FIELDS c_custkey
| LEFT OUTER JOIN left = c, right = o ON c.c_custkey = o.o_custkey
   [
      SEARCH source=orders
      | WHERE o_comment NOT LIKE '%unusual%packages%'
      | FIELDS o_orderkey, o_custkey
   ]
| STATS ...
```

#### top 명령
<a name="supported-ppl-top-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`top` 명령을 사용하여 필드 목록에서 모든 필드 값의 가장 흔한 튜플을 찾습니다.

**구문**  
다음 구문을 사용합니다.

```
top [N] <field-list> [by-clause] top_approx [N] <field-list> [by-clause]
```

**N**
+ 반환할 결과 수.
+ 기본값: 10

**field-list**
+ 필수.
+ 쉼표로 구분된 필드 이름의 목록입니다.

**by-clause**
+ 선택 사항.
+ 결과를 그룹화할 하나 이상의 필드입니다.

**top\$1approx**
+ [HyperLogLog\$1\$1 알고리즘의 예상 카디널리티](https://spark.apache.org/docs/latest/sql-ref-functions-builtin.html)를 사용하여 (n)개의 상위 필드 개수를 근사값으로 계산합니다.

**예 1: 필드에서 가장 흔한 값 찾기**  
이 예에서는 모든 계정에서 가장 흔한 성별을 찾습니다.

PPL 쿼리:

```
os> source=accounts | top gender;
os> source=accounts | top_approx gender;
fetched rows / total rows = 2/2
+----------+
| gender   |
|----------|
| M        |
| F        |
+----------+
```

**예 2: 필드에서 가장 흔한 값 찾기(1로 제한)**  
이 예에서는 모든 계정에서 가장 흔한 단일 성별을 찾습니다.

PPL 쿼리:

```
os> source=accounts | top_approx 1 gender;
fetched rows / total rows = 1/1
+----------+
| gender   |
|----------|
| M        |
+----------+
```

**예 3: 성별별로 그룹화된 가장 흔한 값 찾기**  
이 예에서는 성별별로 그룹화된 모든 계정의 가장 흔한 연령을 찾습니다.

PPL 쿼리:

```
os> source=accounts | top 1 age by gender;
os> source=accounts | top_approx 1 age by gender;
fetched rows / total rows = 2/2
+----------+-------+
| gender   | age   |
|----------+-------|
| F        | 28    |
| M        | 32    |
+----------+-------+
```

#### trendline 명령
<a name="supported-ppl-trendline-commands"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`trendline` 명령을 사용하여 필드의 이동 평균을 계산합니다.

**구문**  
다음 구문을 사용합니다.

```
TRENDLINE [sort <[+|-] sort-field>] SMA(number-of-datapoints, field) [AS alias] [SMA(number-of-datapoints, field) [AS alias]]... 
```

**[\$1\$1-]**
+ 선택 사항.
+ 더하기[\$1]는 NULL/MISSING 값이 맨 처음에 오는 오름차순을 나타냅니다.
+ 빼기[-]는 NULL/MISSING 값이 마지막에 오는 내림차순을 나타냅니다.
+ 기본값: NULL/MISSING 값이 맨 처음에 오는 오름차순입니다.

**sort-field**
+ 정렬을 사용할 경우 필수입니다.
+ 정렬에 사용되는 필드입니다.

**number-of-datapoints**
+ 필수.
+ 이동 평균을 계산하는 데이터 포인트의 수입니다.
+ 0보다 커야 합니다.

**필드**
+ 필수.
+ 이동 평균을 계산해야 하는 필드의 이름입니다.

**별칭**
+ 선택 사항.
+ 이동 평균을 포함하는 결과 열의 이름입니다.

단순 이동 평균(SMA) 유형만 지원됩니다. 다음과 같이 계산됩니다.

```
f[i]: The value of field 'f' in the i-th data-point
n: The number of data-points in the moving window (period)
t: The current time index

SMA(t) = (1/n) * Σ(f[i]), where i = t-n+1 to t
```

**예 1: 온도 시간 단위의 단순 이동 평균 계산**  
이 예에서는 두 개의 데이터 포인트를 사용하여 온도의 단순 이동 평균을 계산합니다.

PPL 쿼리:

```
os> source=t | trendline sma(2, temperature) as temp_trend;
fetched rows / total rows = 5/5
+-----------+---------+--------------------+----------+
|temperature|device-id|           timestamp|temp_trend|
+-----------+---------+--------------------+----------+
|         12|     1492|2023-04-06 17:07:...|      NULL|
|         12|     1492|2023-04-06 17:07:...|      12.0|
|         13|      256|2023-04-06 17:07:...|      12.5|
|         14|      257|2023-04-06 17:07:...|      13.5|
|         15|      258|2023-04-06 17:07:...|      14.5|
+-----------+---------+--------------------+----------+
```

**예 2: 정렬을 사용하여 온도 시간 단위의 단순 이동 평균 계산**  
이 예에서는 device-id를 기준으로 내림차순으로 정렬된 2개 및 3개의 데이터 포인트를 사용하여 온도에 대한 2개의 단순 이동 평균을 계산합니다.

PPL 쿼리:

```
os> source=t | trendline sort - device-id sma(2, temperature) as temp_trend_2 sma(3, temperature) as temp_trend_3;
fetched rows / total rows = 5/5
+-----------+---------+--------------------+------------+------------------+
|temperature|device-id|           timestamp|temp_trend_2|      temp_trend_3|
+-----------+---------+--------------------+------------+------------------+
|         15|      258|2023-04-06 17:07:...|        NULL|              NULL|
|         14|      257|2023-04-06 17:07:...|        14.5|              NULL|
|         13|      256|2023-04-06 17:07:...|        13.5|              14.0|
|         12|     1492|2023-04-06 17:07:...|        12.5|              13.0|
|         12|     1492|2023-04-06 17:07:...|        12.0|12.333333333333334|
+-----------+---------+--------------------+------------+------------------+
```

#### where 명령
<a name="supported-ppl-where-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`where` 명령은 부울 표현식을 사용하여 검색 결과를 필터링합니다. 부울 표현식이 true로 평가될 때만 결과를 반환합니다.

**구문**  
다음 구문을 사용합니다.

```
where <boolean-expression>    
```

**bool-expression**
+ 선택 사항.
+ 부울 값으로 평가할 수 있는 모든 표현식입니다.

**예 1: 조건을 사용하여 결과 세트 필터링**  
이 예에서는 특정 조건을 충족하는 계정 인덱스에서 문서를 가져오는 방법을 보여줍니다.

PPL 쿼리:

```
os> source=accounts | where account_number=1 or gender="F" | fields account_number, gender;
fetched rows / total rows = 2/2
+------------------+----------+
| account_number   | gender   |
|------------------+----------|
| 1                | M        |
| 13               | F        |
+------------------+----------+
```

**추가 예제**  


**논리적 조건이 있는 필터**
+ `source = table | where c = 'test' AND a = 1 | fields a,b,c`
+ `source = table | where c != 'test' OR a > 1 | fields a,b,c | head 1`
+ `source = table | where c = 'test' NOT a > 1 | fields a,b,c`
+ `source = table | where a = 1 | fields a,b,c`
+ `source = table | where a >= 1 | fields a,b,c`
+ `source = table | where a < 1 | fields a,b,c`
+ `source = table | where b != 'test' | fields a,b,c`
+ `source = table | where c = 'test' | fields a,b,c | head 3`
+ `source = table | where ispresent(b)`
+ `source = table | where isnull(coalesce(a, b)) | fields a,b,c | head 3`
+ `source = table | where isempty(a)`
+ `source = table | where isblank(a)`
+ `source = table | where case(length(a) > 6, 'True' else 'False') = 'True'`
+ `source = table | where a between 1 and 4` - 참고 :이 값은 >= 1 및 <= 4, 즉 [1, 4]를 반환합니다.
+ `source = table | where b not between '2024-09-10' and '2025-09-10'` - 참고: b >= '\$1\$1\$1\$1\$1\$1\$1\$1\$1\$1' 및 b <= '2025-09-10'을 반환합니다.
+ `source = table | where cidrmatch(ip, '***********/24')`
+ `source = table | where cidrmatch(ipv6, '2003:db8::/32')`

```
source = table | eval status_category =
    case(a >= 200 AND a < 300, 'Success',
    a >= 300 AND a < 400, 'Redirection',
    a >= 400 AND a < 500, 'Client Error',
    a >= 500, 'Server Error'
    else 'Incorrect HTTP status code')
    | where case(a >= 200 AND a < 300, 'Success',
    a >= 300 AND a < 400, 'Redirection',
    a >= 400 AND a < 500, 'Client Error',
    a >= 500, 'Server Error'
    else 'Incorrect HTTP status code'
    ) = 'Incorrect HTTP status code'
```

```
source = table
    | eval factor = case(a > 15, a - 14, isnull(b), a - 7, a < 3, a + 1 else 1)
    | where case(factor = 2, 'even', factor = 4, 'even', factor = 6, 'even', factor = 8, 'even' else 'odd') = 'even'
    |  stats count() by factor
```

#### 필드 요약
<a name="supported-ppl-field-summary-command"></a>

**참고**  
이 PPL 명령을 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[명령](#supported-ppl-commands).

`fieldsummary` 명령을 사용하여 각 필드의 기본 통계(개수, 고유 개수, 최소, 최대, 평균, stddev, 평균)를 계산하고 각 필드의 데이터 유형을 결정합니다. 이 명령은 이전 파이프와 함께 사용할 수 있으며 이전 파이프를 고려합니다.

**구문**  
다음 구문을 사용합니다. CloudWatch Logs 사용 사례의 경우 쿼리에서 하나의 필드만 지원됩니다.

```
... | fieldsummary <field-list> (nulls=true/false)
```

**includefields**
+ 통계를 사용하여 통합 결과 집합으로 수집할 모든 열의 목록입니다.

**NULL**
+ 선택 사항.
+  true로 설정된 경우 집계 계산에 null 값을 포함합니다(숫자 값의 경우 null을 0으로 대체).

**예제 1.**  
PPL 쿼리:

```
os> source = t | where status_code != 200 | fieldsummary includefields= status_code nulls=true
+------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
| Fields           | COUNT       | COUNT_DISTINCT    |  MIN  |  MAX   |  AVG   |  MEAN   |        STDDEV       | NUlls | TYPEOF |
|------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
| "status_code"    |      2      |         2         | 301   |   403  |  352.0 |  352.0  |  72.12489168102785  |  0    | "int"  |
+------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
```

**예제 2.**  
PPL 쿼리:

```
os> source = t | fieldsummary includefields= id, status_code, request_path nulls=true
+------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
| Fields           | COUNT       | COUNT_DISTINCT    |  MIN  |  MAX   |  AVG   |  MEAN   |        STDDEV       | NUlls | TYPEOF |
|------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
|       "id"       |      6      |         6         | 1     |   6    |  3.5   |   3.5  |  1.8708286933869707  |  0    | "int"  |
+------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
| "status_code"    |      4      |         3         | 200   |   403  |  184.0 |  184.0  |  161.16699413961905 |  2    | "int"  |
+------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
| "request_path"   |      2      |         2         | /about| /home  |  0.0    |  0.0     |      0            |  2    |"string"|
+------------------+-------------+------------+------------+------------+------------+------------+------------+----------------|
```

#### expand 명령
<a name="supported-ppl-expand-command"></a>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

`expand` 명령을 사용하여 Array<Any> 또는 Map<Any> 유형의 필드를 평면화하여 각 요소 또는 키-값 페어마다 개별 행을 생성합니다.

**구문**  
다음 구문을 사용합니다.

```
expand <field> [As alias]
```

**필드**
+ 확장할 필드입니다.
+ 필드는 지원되는 유형이어야 합니다.

**별칭**
+ 선택 사항.
+ 원래 필드 이름 대신 사용할 이름입니다.

**사용 지침**  
expand 명령은 지정된 배열 또는 맵 필드의 각 요소에 해당하는 행을 생성합니다.
+ 배열 요소는 개별 행이 됩니다.
+ 맵 키-값 페어는 별도의 행으로 나뉘며 각 키-값은 행으로 표시됩니다.
+ 별칭이 제공되면 분해된 값이 원래 필드 이름 대신 별칭 아래에 표시됩니다.

이 명령을 stats, eval, parse 등의 다른 명령과 함께 사용하여 확장 후 데이터를 조작하거나 추출할 수 있습니다.

**예제**
+ `source = table | expand employee | stats max(salary) as max by state, company `
+ `source = table | expand employee as worker | stats max(salary) as max by state, company `
+ `source = table | expand employee as worker | eval bonus = salary * 3 | fields worker, bonus` 
+ `source = table | expand employee | parse description '(?<email>.+@.+)' | fields employee, email` 
+ `source = table | eval array=json_array(1, 2, 3) | expand array as uid | fields name, occupation, uid `
+ `source = table | expand multi_valueA as multiA | expand multi_valueB as multiB` 

expand 명령을 eval, stats 등과 같은 다른 명령과 함께 사용할 수 있습니다. 여러 expand 명령을 사용하면 각 복합 배열 또는 맵 내의 모든 내부 요소의 데카르트 곱이 생성됩니다.

**효과적인 SQL 푸시 다운 쿼리**  
expand 명령은 LATERAL VIEW 분해를 사용하여 동등한 SQL 작업으로 변환되므로 SQL 쿼리 수준에서 배열 또는 맵을 효율적으로 분해할 수 있습니다.

```
SELECT customer exploded_productId
FROM table
LATERAL VIEW explode(productId) AS exploded_productId
```

explode 명령은 다음 기능을 제공합니다.
+ 새 열을 반환하는 열 작업입니다.
+ 분해된 열의 모든 요소에 대해 새 행을 생성합니다.
+ 내부 null은 분해된 필드의 일부로 무시됩니다(null에 대한 행이 생성되거나 분해되지 않음).

#### PPL 함수
<a name="supported-ppl-functions-details"></a>

**Topics**
+ [

##### PPL 조건 함수
](#supported-ppl-condition-functions)
+ [

##### PPL 암호화 해시 함수
](#supported-ppl-cryptographic-functions)
+ [

##### PPL 날짜 및 시간 함수
](#supported-ppl-date-time-functions)
+ [

##### PPL 표현식
](#supported-ppl-expressions)
+ [

##### PPL IP 주소 함수
](#supported-ppl-ip-address-functions)
+ [

##### PPL JSON 함수
](#supported-ppl-json-functions)
+ [

##### PPL Lambda 함수
](#supported-ppl-lambda-functions)
+ [

##### PPL 수학 함수
](#supported-ppl-math-functions)
+ [

##### PPL 문자열 함수
](#supported-ppl-string-functions)
+ [

##### PPL 유형 변환 함수
](#supported-ppl-type-conversion-functions)

##### PPL 조건 함수
<a name="supported-ppl-condition-functions"></a>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

##### ISNULL
<a name="supported-ppl-condition-functions-isnull"></a>

**설명**: `isnull(field)`은 필드가 null인 경우 true를 반환합니다.

**인수 유형:**
+ 지원되는 모든 데이터 유형입니다.

**반환 유형:**
+ BOOLEAN

**예:**

```
os> source=accounts | eval result = isnull(employer) | fields result, employer, firstname
fetched rows / total rows = 4/4
+----------+-------------+-------------+
| result   | employer    | firstname   |
|----------+-------------+-------------|
| False    | AnyCompany  | Mary        |
| False    | ExampleCorp | Jane        |
| False    | ExampleOrg  | Nikki       |
| True     | null        | Juan        |
+----------+-------------+-------------+
```

##### ISNOTNULL
<a name="supported-ppl-condition-functions-isnotnull"></a>

**설명**: `isnotnull(field)`은 필드가 null이 아닌 경우 true를 반환합니다.

**인수 유형:**
+ 지원되는 모든 데이터 유형입니다.

**반환 유형:**
+ BOOLEAN

**예:**

```
os> source=accounts | where not isnotnull(employer) | fields account_number, employer
fetched rows / total rows = 1/1
+------------------+------------+
| account_number   | employer   |
|------------------+------------|
| 18               | null       |
+------------------+------------+
```

##### exists
<a name="supported-ppl-condition-functions-exists"></a>

**예:**

```
os> source=accounts | where exists(email) | fields account_number, email
fetched rows / total rows = 1/1
```

##### IFNULL
<a name="supported-ppl-condition-functions-ifnull"></a>

**설명**: `ifnull(field1, field2)`은 `field1`이 null이면 `field2`를 반환합니다.

**인수 유형:**
+ 지원되는 모든 데이터 유형입니다.
+ 두 파라미터의 유형이 다른 경우 함수는 시맨틱 검사에 실패합니다.

**반환 유형:**
+ 임의

**예:**

```
os> source=accounts | eval result = ifnull(employer, 'default') | fields result, employer, firstname
fetched rows / total rows = 4/4
+------------+------------+-------------+
| result     | employer   | firstname   |
|------------+------------+-------------|
| AnyCompany | AnyCompany | Mary        |
| ExampleCorp| ExampleCorp| Jane        |
| ExampleOrg | ExampleOrg | Nikki       |
| default    | null       | Juan        |
+------------+------------+-------------+
```

##### nullIF
<a name="supported-ppl-condition-functions-nullif"></a>

**설명**: `nullif(field1, field2)`은 두 파라미터가 동일한 경우 null을 반환하고, 그렇지 않으면 field1을 반환합니다.

**인수 유형:**
+ 지원되는 모든 데이터 유형입니다.
+ 두 파라미터의 유형이 다른 경우 함수는 시맨틱 검사에 실패합니다.

**반환 유형:**
+ 임의

**예:**

```
os> source=accounts | eval result = nullif(employer, 'AnyCompany') | fields result, employer, firstname
fetched rows / total rows = 4/4
+----------------+----------------+-------------+
| result         | employer       | firstname   |
|----------------+----------------+-------------|
| null           | AnyCompany     | Mary        |
| ExampleCorp    | ExampleCorp    | Jane        |
| ExampleOrg     | ExampleOrg     | Nikki       |
| null           | null           | Juan        |
+----------------+----------------+-------------+
```

##### IF
<a name="supported-ppl-condition-functions-if"></a>

**설명**: `if(condition, expr1, expr2)`는 조건이 true이면 `expr1`을 반환하고, 그렇지 않으면 `expr2`를 반환합니다.

**인수 유형:**
+ 지원되는 모든 데이터 유형입니다.
+ 두 파라미터의 유형이 다른 경우 함수는 시맨틱 검사에 실패합니다.

**반환 유형:**
+ 임의

**예:**

```
os> source=accounts | eval result = if(true, firstname, lastname) | fields result, firstname, lastname
fetched rows / total rows = 4/4
+----------+-------------+----------+
| result   | firstname | lastname   |
|----------+-------------+----------|
| Jane     | Jane      | Doe        |
| Mary     | Mary      | Major      |
| Pat      | Pat       | Candella   |
| Dale     | Jorge     | Souza      |
+----------+-----------+------------+

os> source=accounts | eval result = if(false, firstname, lastname) | fields result, firstname, lastname
fetched rows / total rows = 4/4
+----------+-------------+------------+
| result   | firstname   | lastname   |
|----------+-------------+------------|
| Doe      | Jane        | Doe        |
| Major    | Mary        | Major      |
| Candella | Pat         | Candella   |
| Souza    | Jorge       | Souza      |
+----------+-------------+------------+

os> source=accounts | eval is_vip = if(age > 30 AND isnotnull(employer), true, false) | fields is_vip, firstname, lastname
fetched rows / total rows = 4/4
+----------+-------------+------------+
| is_vip   | firstname   | lastname   |
|----------+-------------+------------|
| True     | Jane        | Doe        |
| True     | Mary        | Major      |
| False    | Pat         | Candella   |
| False    | Jorge       | Souza      |
+----------+-------------+------------+
```

##### PPL 암호화 해시 함수
<a name="supported-ppl-cryptographic-functions"></a>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

##### MD5
<a name="supported-ppl-cryptographic-functions-md5"></a>

MD5는 MD5 다이제스트를 계산하고 값을 32자 16진수 문자열로 반환합니다.

**사용량**: `md5('hello')`

**인수 유형:**
+ STRING

**반환 유형:**
+ STRING

**예:**

```
os> source=people | eval `MD5('hello')` = MD5('hello') | fields `MD5('hello')`
fetched rows / total rows = 1/1
+----------------------------------+
| MD5('hello')                     |
|----------------------------------|
| <32 character hex string>        |
+----------------------------------+
```

##### SHA1
<a name="supported-ppl-cryptographic-functions-sha1"></a>

SHA1은 SHA-1의 16진수 문자열 결과를 반환합니다.

**사용량**: `sha1('hello')`

**인수 유형:**
+ STRING

**반환 유형:**
+ STRING

**예:**

```
os> source=people | eval `SHA1('hello')` = SHA1('hello') | fields `SHA1('hello')`
fetched rows / total rows = 1/1
+------------------------------------------+
| SHA1('hello')                            |
|------------------------------------------|
| <40-character SHA-1 hash result>         |
+------------------------------------------+
```

##### SHA2
<a name="supported-ppl-cryptographic-functions-sha2"></a>

SHA2는 SHA-2 해시 함수 패밀리(SHA-224, SHA-256, SHA-384 및 SHA-512)의 16진수 문자열 결과를 반환합니다. numBits는 결과의 원하는 비트 길이를 나타내며, 값은 224, 256, 384, 512여야 합니다.

**사용량:**
+ `sha2('hello',256)`
+ `sha2('hello',512)`

**인수 유형:**
+ STRING, INTEGER

**반환 유형:**
+ STRING

**예:**

```
os> source=people | eval `SHA2('hello',256)` = SHA2('hello',256) | fields `SHA2('hello',256)`
fetched rows / total rows = 1/1
+------------------------------------------------------------------+
| SHA2('hello',256)                                                |
|------------------------------------------------------------------|
| <64-character SHA-256 hash result>                               |
+------------------------------------------------------------------+

os> source=people | eval `SHA2('hello',512)` = SHA2('hello',512) | fields `SHA2('hello',512)`
fetched rows / total rows = 1/1
+------------------------------------------------------------------+
| SHA2('hello',512)                                                |                                                                |
|------------------------------------------------------------------|
| <128-character SHA-512 hash result>                              |
+------------------------------------------------------------------+
```

##### PPL 날짜 및 시간 함수
<a name="supported-ppl-date-time-functions"></a>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

##### `DAY`
<a name="supported-ppl-date-time-functions-day"></a>

**사용**: `DAY(date)`는 날짜의 월간 날짜를 1\$131 범위로 추출합니다.

**인수 유형**: STRING/DATE/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `DAYOFMONTH`, `DAY_OF_MONTH` 

**예:**

```
os> source=people | eval `DAY(DATE('2020-08-26'))` = DAY(DATE('2020-08-26')) | fields `DAY(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+---------------------------+
| DAY(DATE('2020-08-26'))   |
|---------------------------|
| 26                        |
+---------------------------+
```

##### `DAYOFMONTH`
<a name="supported-ppl-date-time-functions-dayofmonth"></a>

**사용**: `DAYOFMONTH(date)`는 날짜의 월간 날짜를 1\$131 범위로 추출합니다.

**인수 유형**: STRING/DATE/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `DAY`, `DAY_OF_MONTH` 

**예:**

```
os> source=people | eval `DAYOFMONTH(DATE('2020-08-26'))` = DAYOFMONTH(DATE('2020-08-26')) | fields `DAYOFMONTH(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+----------------------------------+
| DAYOFMONTH(DATE('2020-08-26'))   |
|----------------------------------|
| 26                               |
+----------------------------------+
```

##### `DAY_OF_MONTH`
<a name="supported-ppl-date-time-functions-day-of-month"></a>

**사용**: `DAY_OF_MONTH(DATE)`는 날짜의 월간 날짜를 1\$131 범위로 추출합니다.

**인수 유형**: STRING/DATE/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `DAY`, `DAYOFMONTH` 

**예:**

```
os> source=people | eval `DAY_OF_MONTH(DATE('2020-08-26'))` = DAY_OF_MONTH(DATE('2020-08-26')) | fields `DAY_OF_MONTH(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+------------------------------------+
| DAY_OF_MONTH(DATE('2020-08-26'))   |
|------------------------------------|
| 26                                 |
+------------------------------------+
```

##### `DAYOFWEEK`
<a name="supported-ppl-date-time-functions-dayofweek"></a>

**사용**: `DAYOFWEEK(DATE)`는 날짜의 요일 인덱스를 반환합니다(1 = 일요일, 2 = 월요일, ..., 7 = 토요일).

**인수 유형**: STRING/DATE/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `DAY_OF_WEEK`

**예:**

```
os> source=people | eval `DAYOFWEEK(DATE('2020-08-26'))` = DAYOFWEEK(DATE('2020-08-26')) | fields `DAYOFWEEK(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+---------------------------------+
| DAYOFWEEK(DATE('2020-08-26'))   |
|---------------------------------|
| 4                               |
+---------------------------------+
```

##### `DAY_OF_WEEK`
<a name="supported-ppl-date-time-functions-day-of-week"></a>

**사용**: `DAY_OF_WEEK(DATE)`는 날짜의 요일 인덱스를 반환합니다(1 = 일요일, 2 = 월요일, ..., 7 = 토요일).

**인수 유형**: STRING/DATE/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `DAYOFWEEK`

**예:**

```
os> source=people | eval `DAY_OF_WEEK(DATE('2020-08-26'))` = DAY_OF_WEEK(DATE('2020-08-26')) | fields `DAY_OF_WEEK(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+-----------------------------------+
| DAY_OF_WEEK(DATE('2020-08-26'))   |
|-----------------------------------|
| 4                                 |
+-----------------------------------+
```

##### `DAYOFYEAR`
<a name="supported-ppl-date-time-functions-dayofyear"></a>

**사용**: `DAYOFYEAR(DATE)`는 1\$1366 범위로 날짜의 연중 날짜를 반환합니다.

**인수 유형**: STRING/DATE/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `DAY_OF_YEAR`

**예:**

```
os> source=people | eval `DAYOFYEAR(DATE('2020-08-26'))` = DAYOFYEAR(DATE('2020-08-26')) | fields `DAYOFYEAR(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+---------------------------------+
| DAYOFYEAR(DATE('2020-08-26'))   |
|---------------------------------|
| 239                             |
+---------------------------------+
```

##### `DAY_OF_YEAR`
<a name="supported-ppl-date-time-functions-day-of-year"></a>

**사용**: `DAY_OF_YEAR(DATE)`는 1\$1366 범위로 날짜의 연중 날짜를 반환합니다.

**인수 유형**: STRING/DATE/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `DAYOFYEAR`

**예:**

```
os> source=people | eval `DAY_OF_YEAR(DATE('2020-08-26'))` = DAY_OF_YEAR(DATE('2020-08-26')) | fields `DAY_OF_YEAR(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+-----------------------------------+
| DAY_OF_YEAR(DATE('2020-08-26'))   |
|-----------------------------------|
| 239                               |
+-----------------------------------+
```

##### `DAYNAME`
<a name="supported-ppl-date-time-functions-dayname"></a>

**사용**: `DAYNAME(DATE)`는 월요일, 화요일, 수요일, 목요일, 금요일, 토요일, 일요일을 포함한 날짜의 요일 이름을 반환합니다.

**인수 유형**: STRING/DATE/TIMESTAMP

**반환 유형**: STRING

**예:**

```
os> source=people | eval `DAYNAME(DATE('2020-08-26'))` = DAYNAME(DATE('2020-08-26')) | fields `DAYNAME(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+-------------------------------+
| DAYNAME(DATE('2020-08-26'))   |
|-------------------------------|
| Wednesday                     |
+-------------------------------+
```

##### `FROM_UNIXTIME`
<a name="supported-ppl-date-time-functions-from-unixtime"></a>

**사용**: `FROM_UNIXTIME`은 타임스탬프 또는 문자열 값으로 제공된 인수의 표현을 반환합니다. 이 함수는 `UNIX_TIMESTAMP` 함수의 역변환을 수행합니다.

두 번째 인수를 제공할 경우 `FROM_UNIXTIME`은 해당 인수를 사용하여 결과를 `DATE_FORMAT` 함수와 유사한 형식으로 지정합니다.

이 함수는 타임스탬프가 1970-01-01 00:00:00\$13001-01-18 23:59:59.999999(0\$132536771199.999999 에포크 시간) 범위를 벗어날 경우 `NULL`을 반환합니다.

**인수 유형**: DOUBLE, STRING

**반환 유형 맵**:

DOUBLE -> TIMESTAMP

DOUBLE, STRING -> STRING

**예**:

```
os> source=people | eval `FROM_UNIXTIME(1220249547)` = FROM_UNIXTIME(1220249547) | fields `FROM_UNIXTIME(1220249547)`
fetched rows / total rows = 1/1
+-----------------------------+
| FROM_UNIXTIME(1220249547)   |
|-----------------------------|
| 2008-09-01 06:12:27         |
+-----------------------------+

os> source=people | eval `FROM_UNIXTIME(1220249547, 'HH:mm:ss')` = FROM_UNIXTIME(1220249547, 'HH:mm:ss') | fields `FROM_UNIXTIME(1220249547, 'HH:mm:ss')`
fetched rows / total rows = 1/1
+-----------------------------------------+
| FROM_UNIXTIME(1220249547, 'HH:mm:ss')   |
|-----------------------------------------|
| 06:12:27                                |
+-----------------------------------------+
```

##### `HOUR`
<a name="supported-ppl-date-time-functions-hour"></a>

**사용**: `HOUR(TIME)`는 시간의 시각 값을 추출합니다.

표준 시간대와 달리 이 함수의 시간 값은 23보다 큰 범위를 가질 수 있습니다. 따라서 `HOUR(TIME)`의 반환 값이 23보다 클 수 있습니다.

**인수 유형**: STRING/TIME/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `HOUR_OF_DAY`

**예:**

```
os> source=people | eval `HOUR(TIME('01:02:03'))` = HOUR(TIME('01:02:03')) | fields `HOUR(TIME('01:02:03'))`
fetched rows / total rows = 1/1
+--------------------------+
| HOUR(TIME('01:02:03'))   |
|--------------------------|
| 1                        |
+--------------------------+
```

##### `HOUR_OF_DAY`
<a name="supported-ppl-date-time-functions-hour-of-day"></a>

**사용**: `HOUR_OF_DAY(TIME)`는 지정된 시간에서 시각 값을 추출합니다.

표준 시간대와 달리 이 함수의 시간 값은 23보다 큰 범위를 가질 수 있습니다. 따라서 `HOUR_OF_DAY(TIME)`의 반환 값이 23보다 클 수 있습니다.

**인수 유형**: STRING/TIME/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `HOUR`

**예:**

```
os> source=people | eval `HOUR_OF_DAY(TIME('01:02:03'))` = HOUR_OF_DAY(TIME('01:02:03')) | fields `HOUR_OF_DAY(TIME('01:02:03'))`
fetched rows / total rows = 1/1
+---------------------------------+
| HOUR_OF_DAY(TIME('01:02:03'))   |
|---------------------------------|
| 1                               |
+---------------------------------+
```

##### `LAST_DAY`
<a name="supported-ppl-date-time-functions-last-day"></a>

**사용**: `LAST_DAY`는 지정된 날짜 인수에 대한 DATE 값으로 해당 월의 마지막 날짜를 반환합니다.

**인수 유형**: DATE/STRING/TIMESTAMP/TIME

**반환 유형**: DATE

**예:**

```
os> source=people | eval `last_day('2023-02-06')` = last_day('2023-02-06') | fields `last_day('2023-02-06')`
fetched rows / total rows = 1/1
+--------------------------+
| last_day('2023-02-06')   |
|--------------------------|
| 2023-02-28               |
+--------------------------+
```

##### `LOCALTIMESTAMP`
<a name="supported-ppl-date-time-functions-localtimestamp"></a>

**사용**: `LOCALTIMESTAMP()`는 `NOW()`의 동의어입니다.

**예:**

```
> source=people | eval `LOCALTIMESTAMP()` = LOCALTIMESTAMP() | fields `LOCALTIMESTAMP()`
fetched rows / total rows = 1/1
+---------------------+
| LOCALTIMESTAMP()    |
|---------------------|
| 2022-08-02 15:54:19 |
+---------------------+
```

##### `LOCALTIME`
<a name="supported-ppl-date-time-functions-localtime"></a>

**사용**: `LOCALTIME()`은 `NOW()`의 동의어입니다.

**예:**

```
> source=people | eval `LOCALTIME()` = LOCALTIME() | fields `LOCALTIME()`
fetched rows / total rows = 1/1
+---------------------+
| LOCALTIME()         |
|---------------------|
| 2022-08-02 15:54:19 |
+---------------------+
```

##### `MAKE_DATE`
<a name="supported-ppl-date-time-functions-make-date"></a>

**사용**: `MAKE_DATE`는 지정된 연도, 월 및 일 값을 기준으로 날짜 값을 반환합니다. 모든 인수는 정수로 반올림됩니다.

**사양**: 1. MAKE\$1DATE(INTEGER, INTEGER, INTEGER) -> DATE

**인수 유형**: INTEGER, INTEGER, INTEGER

**반환 유형**: DATE

**예:**

```
os> source=people | eval `MAKE_DATE(1945, 5, 9)` = MAKEDATE(1945, 5, 9) | fields `MAKEDATE(1945, 5, 9)`
fetched rows / total rows = 1/1
+------------------------+
| MAKEDATE(1945, 5, 9)   |
|------------------------|
| 1945-05-09             |
+------------------------+
```

##### `MINUTE`
<a name="supported-ppl-date-time-functions-minute"></a>

**사용**: `MINUTE(TIME)`는 지정된 시간의 분 구성 요소를 0\$159 범위의 정수로 반환합니다.

**인수 유형**: STRING/TIME/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `MINUTE_OF_HOUR`

**예:**

```
os> source=people | eval `MINUTE(TIME('01:02:03'))` =  MINUTE(TIME('01:02:03')) | fields `MINUTE(TIME('01:02:03'))`
fetched rows / total rows = 1/1
+----------------------------+
| MINUTE(TIME('01:02:03'))   |
|----------------------------|
| 2                          |
+----------------------------+
```

##### `MINUTE_OF_HOUR`
<a name="supported-ppl-date-time-functions-minute-of-hour"></a>

**사용**: `MINUTE_OF_HOUR(TIME)`는 지정된 시간의 분 구성 요소를 0\$159 범위의 정수로 반환합니다.

**인수 유형**: STRING/TIME/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `MINUTE`

**예:**

```
os> source=people | eval `MINUTE_OF_HOUR(TIME('01:02:03'))` =  MINUTE_OF_HOUR(TIME('01:02:03')) | fields `MINUTE_OF_HOUR(TIME('01:02:03'))`
fetched rows / total rows = 1/1
+------------------------------------+
| MINUTE_OF_HOUR(TIME('01:02:03'))   |
|------------------------------------|
| 2                                  |
+------------------------------------+
```

##### `MONTH`
<a name="supported-ppl-date-time-functions-month"></a>

**사용**: `MONTH(DATE)`는 지정된 날짜의 월을 1\$112 범위의 정수로 반환합니다(여기서 1은 1월을 나타내고 12는 12월을 나타냄).

**인수 유형**: STRING/DATE/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `MONTH_OF_YEAR`

**예:**

```
os> source=people | eval `MONTH(DATE('2020-08-26'))` =  MONTH(DATE('2020-08-26')) | fields `MONTH(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+-----------------------------+
| MONTH(DATE('2020-08-26'))   |
|-----------------------------|
| 8                           |
+-----------------------------+
```

##### `MONTHNAME`
<a name="supported-ppl-date-time-functions-monthname"></a>

**사용**: `MONTHNAME(DATE)`는 지정된 날짜의 월을 1\$112 범위의 정수로 반환합니다(여기서 1은 1월을 나타내고 12는 12월을 나타냄).

**인수 유형**: STRING/DATE/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `MONTH_OF_YEAR`

**예:**

```
os> source=people | eval `MONTHNAME(DATE('2020-08-26'))` = MONTHNAME(DATE('2020-08-26')) | fields `MONTHNAME(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+---------------------------------+
| MONTHNAME(DATE('2020-08-26'))   |
|---------------------------------|
| August                          |
+---------------------------------+
```

##### `MONTH_OF_YEAR`
<a name="supported-ppl-date-time-functions-month-of-year"></a>

**사용**: `MONTH_OF_YEAR(DATE)`는 지정된 날짜의 월을 1\$112 범위의 정수로 반환합니다(여기서 1은 1월을 나타내고 12는 12월을 나타냄).

**인수 유형**: STRING/DATE/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `MONTH`

**예:**

```
os> source=people | eval `MONTH_OF_YEAR(DATE('2020-08-26'))` =  MONTH_OF_YEAR(DATE('2020-08-26')) | fields `MONTH_OF_YEAR(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+-------------------------------------+
| MONTH_OF_YEAR(DATE('2020-08-26'))   |
|-------------------------------------|
| 8                                   |
+-------------------------------------+
```

##### `NOW`
<a name="supported-ppl-date-time-functions-now"></a>

**사용**: `NOW`는 현재 날짜 및 시간을 'YYYY-MM-DD hh:mm:ss' 형식의 `TIMESTAMP` 값으로 반환합니다. 이 값은 클러스터 시간대로 표시됩니다.

**참고**  
`NOW()`는 문이 실행되기 시작한 시간을 나타내는 일정한 시간을 반환합니다. 이는 정확한 실행 시간을 반환하는 `SYSDATE()`와 다릅니다.

**반환 유형**: TIMESTAMP

**사양**: NOW() -> TIMESTAMP

**예:**

```
os> source=people | eval `value_1` = NOW(), `value_2` = NOW() | fields `value_1`, `value_2`
fetched rows / total rows = 1/1
+---------------------+---------------------+
| value_1             | value_2             |
|---------------------+---------------------|
| 2022-08-02 15:39:05 | 2022-08-02 15:39:05 |
+---------------------+---------------------+
```

##### `QUARTER`
<a name="supported-ppl-date-time-functions-quarter"></a>

**사용**: `QUARTER(DATE)`는 지정된 날짜의 분기를 1\$14 범위의 정수로 반환합니다.

**인수 유형**: STRING/DATE/TIMESTAMP

**반환 유형**: INTEGER

**예:**

```
os> source=people | eval `QUARTER(DATE('2020-08-26'))` = QUARTER(DATE('2020-08-26')) | fields `QUARTER(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+-------------------------------+
| QUARTER(DATE('2020-08-26'))   |
|-------------------------------|
| 3                             |
+-------------------------------+
```

##### `SECOND`
<a name="supported-ppl-date-time-functions-second"></a>

**사용**: `SECOND(TIME)`는 지정된 시간의 초 구성 요소를 0\$159 범위의 정수로 반환합니다.

**인수 유형**: STRING/TIME/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `SECOND_OF_MINUTE`

**예:**

```
os> source=people | eval `SECOND(TIME('01:02:03'))` = SECOND(TIME('01:02:03')) | fields `SECOND(TIME('01:02:03'))`
fetched rows / total rows = 1/1
+----------------------------+
| SECOND(TIME('01:02:03'))   |
|----------------------------|
| 3                          |
+----------------------------+
```

##### `SECOND_OF_MINUTE`
<a name="supported-ppl-date-time-functions-second-of-minute"></a>

**사용**: `SECOND_OF_MINUTE(TIME)`는 지정된 시간의 초 구성 요소를 0\$159 범위의 정수로 반환합니다.

**인수 유형**: STRING/TIME/TIMESTAMP

**반환 유형**: INTEGER

**동의어**: `SECOND`

**예:**

```
os> source=people | eval `SECOND_OF_MINUTE(TIME('01:02:03'))` = SECOND_OF_MINUTE(TIME('01:02:03')) | fields `SECOND_OF_MINUTE(TIME('01:02:03'))`
fetched rows / total rows = 1/1
+--------------------------------------+
| SECOND_OF_MINUTE(TIME('01:02:03'))   |
|--------------------------------------|
| 3                                    |
+--------------------------------------+
```

##### `SUBDATE`
<a name="supported-ppl-date-time-functions-subdate"></a>

**사용**: `SUBDATE(DATE, DAYS)`는 지정된 날짜에서 두 번째 인수(예: `DATE` 또는 `DAYS`)를 뺍니다.

**인수 유형**: DATE/TIMESTAMP, LONG

**반환 유형 맵**: (DATE, LONG) -> DATE

**반의어:** `ADDDATE`

**예:**

```
os> source=people | eval `'2008-01-02' - 31d` = SUBDATE(DATE('2008-01-02'), 31), `'2020-08-26' - 1` = SUBDATE(DATE('2020-08-26'), 1), `ts '2020-08-26 01:01:01' - 1` = SUBDATE(TIMESTAMP('2020-08-26 01:01:01'), 1) | fields `'2008-01-02' - 31d`, `'2020-08-26' - 1`, `ts '2020-08-26 01:01:01' - 1`
fetched rows / total rows = 1/1
+----------------------+--------------------+--------------------------------+
| '2008-01-02' - 31d   | '2020-08-26' - 1   | ts '2020-08-26 01:01:01' - 1   |
|----------------------+--------------------+--------------------------------|
| 2007-12-02 00:00:00  | 2020-08-25         | 2020-08-25 01:01:01            |
+----------------------+--------------------+--------------------------------+
```

##### `SYSDATE`
<a name="supported-ppl-date-time-functions-sysdate"></a>

**사용**: `SYSDATE()`는 현재 날짜 및 시간을 'YYYY-MM-DD hh:mm:ss.nnnnnn' 형식의 `TIMESTAMP` 값으로 반환합니다.

`SYSDATE()`는 실행되는 정확한 시간을 반환합니다. 이는 문이 실행되기 시작한 시점을 나타내는 일정한 시간을 반환하는 NOW()와 다릅니다.

**선택적 인수 유형**: INTEGER(0\$16) - 반환 값에서 초의 소수 자릿수를 지정합니다.

**반환 유형**: TIMESTAMP

**예:**

```
os> source=people | eval `SYSDATE()` = SYSDATE() | fields `SYSDATE()`
fetched rows / total rows = 1/1
+----------------------------+
| SYSDATE()                  |
|----------------------------|
| 2022-08-02 15:39:05.123456 |
+----------------------------+
```

##### `TIMESTAMP`
<a name="supported-ppl-date-time-functions-timestamp"></a>

**사용**: `TIMESTAMP(EXPR)`는 입력 문자열 `expr`을 타임스탬프로 사용하여 타임스탬프 유형을 구성합니다.

`TIMESTAMP(expr)`는 단일 인수를 사용하여 입력에서 타임스탬프를 구성합니다. `expr`이 문자열인 경우 타임스탬프로 해석됩니다. 문자열이 아닌 인수의 경우 이 함수는 UTC 시간대를 사용하여 `expr`을 타임스탬프로 캐스팅합니다. `expr`이 `TIME` 값인 경우 이 함수는 캐스팅 전 오늘 날짜를 적용합니다.

두 인수와 함께 사용할 경우 `TIMESTAMP(expr1, expr2)`는 날짜 또는 타임스탬프 표현식(`expr2`)에 시간 표현식(`expr1`)을 추가하고 결과를 타임스탬프 값으로 반환합니다.

**인수 유형**: STRING/DATE/TIME/TIMESTAMP

**반환 유형 맵**:

(STRING/DATE/TIME/TIMESTAMP) -> TIMESTAMP

(STRING/DATE/TIME/TIMESTAMP, STRING/DATE/TIME/TIMESTAMP) -> TIMESTAMP

**예:**

```
os> source=people | eval `TIMESTAMP('2020-08-26 13:49:00')` = TIMESTAMP('2020-08-26 13:49:00'), `TIMESTAMP('2020-08-26 13:49:00', TIME('12:15:42'))` = TIMESTAMP('2020-08-26 13:49:00', TIME('12:15:42')) | fields `TIMESTAMP('2020-08-26 13:49:00')`, `TIMESTAMP('2020-08-26 13:49:00', TIME('12:15:42'))`
fetched rows / total rows = 1/1
+------------------------------------+------------------------------------------------------+
| TIMESTAMP('2020-08-26 13:49:00')   | TIMESTAMP('2020-08-26 13:49:00', TIME('12:15:42'))   |
|------------------------------------+------------------------------------------------------|
| 2020-08-26 13:49:00                | 2020-08-27 02:04:42                                  |
+------------------------------------+------------------------------------------------------+
```

##### `UNIX_TIMESTAMP`
<a name="supported-ppl-date-time-functions-unix-timestamp"></a>

**사용**: `UNIX_TIMESTAMP`는 지정된 날짜 인수를 Unix 시간(1970년 초에 시작된 에포크 이후 경과된 초)으로 변환합니다. 인수가 제공되지 않으면 현재 Unix 시간을 반환합니다.

날짜 인수는 `DATE`, `TIMESTAMP` 문자열 또는 `YYMMDD`, `YYMMDDhhmmss`, `YYYYMMDD`, `YYYYMMDDhhmmss` 형식 중 하나의 숫자일 수 있습니다. 인수에 시간 구성 요소가 포함된 경우 선택적으로 소수 초를 포함할 수 있습니다.

인수가 잘못된 형식이거나 1970-01-01 00:00:00 to 3001-01-18 23:59:59.999999(에포크 시간 기준 0\$132536771199.999999) 범위를 벗어나는 경우 이 함수는 `NULL`을 반환합니다.

이 함수는 `DATE`, `TIMESTAMP`또는 `DOUBLE`을 인수 유형으로 받거나, 인수를 받지 않습니다. 항상 Unix 타임스탬프를 나타내는 `DOUBLE` 값을 반환합니다.

역변환의 경우 FROM\$1UNIXTIME 함수를 사용할 수 있습니다.

**인수 유형**: <NONE>/DOUBLE/DATE/TIMESTAMP

**반환 유형**: DOUBLE

**예:**

```
os> source=people | eval `UNIX_TIMESTAMP(double)` = UNIX_TIMESTAMP(20771122143845), `UNIX_TIMESTAMP(timestamp)` = UNIX_TIMESTAMP(TIMESTAMP('1996-11-15 17:05:42')) | fields `UNIX_TIMESTAMP(double)`, `UNIX_TIMESTAMP(timestamp)`
fetched rows / total rows = 1/1
+--------------------------+-----------------------------+
| UNIX_TIMESTAMP(double)   | UNIX_TIMESTAMP(timestamp)   |
|--------------------------+-----------------------------|
| 3404817525.0             | 848077542.0                 |
+--------------------------+-----------------------------+
```

##### `WEEK`
<a name="supported-ppl-date-time-functions-week"></a>

**사용**: `WEEK(DATE)`는 지정된 날짜의 주 번호를 반환합니다.

**인수 유형**: DATE/TIMESTAMP/STRING

**반환 유형**: INTEGER

**동의어**: `WEEK_OF_YEAR`

**예:**

```
os> source=people | eval `WEEK(DATE('2008-02-20'))` = WEEK(DATE('2008-02-20')) | fields `WEEK(DATE('2008-02-20'))`
fetched rows / total rows = 1/1
+----------------------------+
| WEEK(DATE('2008-02-20'))   |
|----------------------------|
| 8                          |
+----------------------------+
```

##### `WEEKDAY`
<a name="supported-ppl-date-time-functions-weekday"></a>

**사용**: `WEEKDAY(DATE)`는 날짜의 요일 인덱스(0 = 월요일, 1 = 화요일, ..., 6 = 일요일)를 반환합니다.

`dayofweek` 함수와 비슷하지만 매일 다른 인덱스를 반환합니다.

**인수 유형**: STRING/DATE/TIME/TIMESTAMP

**반환 유형**: INTEGER

**예:**

```
os> source=people | eval `weekday(DATE('2020-08-26'))` = weekday(DATE('2020-08-26')) | eval `weekday(DATE('2020-08-27'))` = weekday(DATE('2020-08-27')) | fields `weekday(DATE('2020-08-26'))`, `weekday(DATE('2020-08-27'))`
fetched rows / total rows = 1/1
+-------------------------------+-------------------------------+
| weekday(DATE('2020-08-26'))   | weekday(DATE('2020-08-27'))   |
|-------------------------------+-------------------------------|
| 2                             | 3                             |
+-------------------------------+-------------------------------+
```

##### `WEEK_OF_YEAR`
<a name="supported-ppl-date-time-functions-week-of-year"></a>

**사용**: `WEEK_OF_YEAR(DATE)`는 지정된 날짜의 주 번호를 반환합니다.

**인수 유형**: DATE/TIMESTAMP/STRING

**반환 유형**: INTEGER

**동의어**: `WEEK`

**예:**

```
os> source=people | eval `WEEK_OF_YEAR(DATE('2008-02-20'))` = WEEK(DATE('2008-02-20'))| fields `WEEK_OF_YEAR(DATE('2008-02-20'))`
fetched rows / total rows = 1/1
+------------------------------------+
| WEEK_OF_YEAR(DATE('2008-02-20'))   |
|------------------------------------|
| 8                                  |
+------------------------------------+
```

##### `YEAR`
<a name="supported-ppl-date-time-functions-year"></a>

**사용**: `YEAR(DATE)`는 1000\$19999 범위로 날짜의 연도를 반환하거나, 날짜가 '0'인 경우 0을 반환합니다.

**인수 유형**: STRING/DATE/TIMESTAMP

**반환 유형**: INTEGER

**예:**

```
os> source=people | eval `YEAR(DATE('2020-08-26'))` = YEAR(DATE('2020-08-26')) | fields `YEAR(DATE('2020-08-26'))`
fetched rows / total rows = 1/1
+----------------------------+
| YEAR(DATE('2020-08-26'))   |
|----------------------------|
| 2020                       |
+----------------------------+
```

##### `DATE_ADD`
<a name="supported-ppl-date-time-functions-date-add"></a>

**사용**: `DATE_ADD(date, INTERVAL expr unit)`는 지정된 날짜에 지정된 간격을 추가합니다.

**인수 유형**: DATE, INTERVAL

**반환 유형**: DATE

**반의어:** `DATE_SUB`

**예:**

```
os> source=people | eval `'2020-08-26' + 1d` = DATE_ADD(DATE('2020-08-26'), INTERVAL 1 DAY) | fields `'2020-08-26' + 1d`
fetched rows / total rows = 1/1
+---------------------+
| '2020-08-26' + 1d   |
|---------------------|
| 2020-08-27          |
+---------------------+
```

##### `DATE_SUB`
<a name="supported-ppl-date-time-functions-date-sub"></a>

**사용량**: `DATE_SUB(date, INTERVAL expr unit)`는 날짜에서 간격 expr을 뺍니다.

**인수 유형**: DATE, INTERVAL

**반환 유형**: DATE

**반의어:** `DATE_ADD`

**예:**

```
os> source=people | eval `'2008-01-02' - 31d` = DATE_SUB(DATE('2008-01-02'), INTERVAL 31 DAY) | fields `'2008-01-02' - 31d`
fetched rows / total rows = 1/1
+---------------------+
| '2008-01-02' - 31d  |
|---------------------|
| 2007-12-02          |
+---------------------+
```

##### `TIMESTAMPADD`
<a name="supported-ppl-date-time-functions-timestampadd"></a>

**사용량**: `TIMESTAMP`는 지정된 날짜에 지정된 시간 간격을 추가한 후 값을 반환합니다.

**인수**: 
+ interval: INTERVAL(SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR) 
+ integer: INTEGER 
+ date: DATE, TIMESTAMP 또는 STRING

`STRING`을 날짜 인수로 제공하는 경우 유효한 `TIMESTAMP`로 형식을 지정합니다. 이 함수는 `DATE` 인수를 `TIMESTAMP`로 자동 변환합니다.

**예**:

```
os> source=people | eval `TIMESTAMPADD(DAY, 17, '2000-01-01 00:00:00')` = TIMESTAMPADD(DAY, 17, '2000-01-01 00:00:00') | eval `TIMESTAMPADD(QUARTER, -1, '2000-01-01 00:00:00')` = TIMESTAMPADD(QUARTER, -1, '2000-01-01 00:00:00') | fields `TIMESTAMPADD(DAY, 17, '2000-01-01 00:00:00')`, `TIMESTAMPADD(QUARTER, -1, '2000-01-01 00:00:00')`
fetched rows / total rows = 1/1
+----------------------------------------------+--------------------------------------------------+
| TIMESTAMPADD(DAY, 17, '2000-01-01 00:00:00') | TIMESTAMPADD(QUARTER, -1, '2000-01-01 00:00:00') |
|----------------------------------------------+--------------------------------------------------|
| 2000-01-18 00:00:00                          | 1999-10-01 00:00:00                              |
+----------------------------------------------+--------------------------------------------------+
```

##### `TIMESTAMPDIFF`
<a name="supported-ppl-date-time-functions-timestampdiff"></a>

**사용**: `TIMESTAMPDIFF(interval, start, end)`는 지정된 간격 단위로 시작 날짜/시간과 종료 날짜/시간 간의 차이를 반환합니다.

**인수**: 
+ interval: INTERVAL(SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, YEAR) 
+ start: DATE, TIMESTAMP 또는 STRING 
+ end: DATE, TIMESTAMP 또는 STRING

이 함수는 적절한 경우 인수를 `TIMESTAMP`로 자동 변환합니다. `STRING` 인수를 유효한 `TIMESTAMP`로 포맷합니다.

**예**:

```
os> source=people | eval `TIMESTAMPDIFF(YEAR, '1997-01-01 00:00:00', '2001-03-06 00:00:00')` = TIMESTAMPDIFF(YEAR, '1997-01-01 00:00:00', '2001-03-06 00:00:00') | eval `TIMESTAMPDIFF(SECOND, timestamp('1997-01-01 00:00:23'), timestamp('1997-01-01 00:00:00'))` = TIMESTAMPDIFF(SECOND, timestamp('1997-01-01 00:00:23'), timestamp('1997-01-01 00:00:00')) | fields `TIMESTAMPDIFF(YEAR, '1997-01-01 00:00:00', '2001-03-06 00:00:00')`, `TIMESTAMPDIFF(SECOND, timestamp('1997-01-01 00:00:23'), timestamp('1997-01-01 00:00:00'))`
fetched rows / total rows = 1/1
+-------------------------------------------------------------------+-------------------------------------------------------------------------------------------+
| TIMESTAMPDIFF(YEAR, '1997-01-01 00:00:00', '2001-03-06 00:00:00') | TIMESTAMPDIFF(SECOND, timestamp('1997-01-01 00:00:23'), timestamp('1997-01-01 00:00:00')) |
|-------------------------------------------------------------------+-------------------------------------------------------------------------------------------|
| 4                                                                 | -23                                                                                       |
+-------------------------------------------------------------------+-------------------------------------------------------------------------------------------+
```

##### `UTC_TIMESTAMP`
<a name="supported-ppl-date-time-functions-utc-timestamp"></a>

**사용**: `UTC_TIMESTAMP`는 현재 UTC 타임스탬프를 'YYYY-MM-DD hh:mm:ss' 형식의 값으로 반환합니다.

**반환 유형**: TIMESTAMP

**사양**: UTC\$1TIMESTAMP() -> TIMESTAMP

**예:**

```
> source=people | eval `UTC_TIMESTAMP()` = UTC_TIMESTAMP() | fields `UTC_TIMESTAMP()`
fetched rows / total rows = 1/1
+---------------------+
| UTC_TIMESTAMP()     |
|---------------------|
| 2022-10-03 17:54:28 |
+---------------------+
```

##### `CURRENT_TIMEZONE`
<a name="supported-ppl-date-time-functions-current-timezone"></a>

**사용**: `CURRENT_TIMEZONE`은 현재 현지 시간대를 반환합니다.

**반환 유형**: STRING

**예:**

```
> source=people | eval `CURRENT_TIMEZONE()` = CURRENT_TIMEZONE() | fields `CURRENT_TIMEZONE()`
fetched rows / total rows = 1/1
+------------------------+
| CURRENT_TIMEZONE()     |
|------------------------|
| America/Chicago        |
+------------------------+
```

##### PPL 표현식
<a name="supported-ppl-expressions"></a>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

표현식, 특히 값 표현식은 스칼라 값을 반환합니다. 표현식의 유형과 형식은 다릅니다. 예를 들어 원자 표현식과 그에 따라 작성된 산술, 조건자 및 함수 표현식으로 리터럴 값이 존재합니다. `Filter` 및 `Stats` 명령에 산술 표현식을 사용하는 등, 다양한 절에서 표현식을 사용할 수 있습니다.

**연산자**

산술 표현식은 다음과 같이 숫자 리터럴과 바이너리 산술 연산자로 구성된 표현식입니다.

1. `+`: 더하기.

1. `-`: 빼기.

1. `*`: 곱하기.

1. `/`: 나누기(정수의 경우 결과는 소수 부분이 삭제된 정수)

1. `%`: 모듈로(정수에만 사용, 결과는 나누기의 나머지)

**우선 순위**

괄호를 사용하여 산술 연산자의 우선순위를 제어합니다. 그렇지 않으면 우선순위가 더 높은 연산자가 먼저 수행됩니다.

**유형 변환**

연산자 서명을 조회할 때 암시적 유형 변환이 수행됩니다. 예를 들어 정수 `+` 실수는 서명 `+(double,double)`과 일치하여 결과는 실수가 됩니다. 이 규칙은 함수 호출에도 적용됩니다.

다양한 유형의 산술 표현식의 예:

```
os> source=accounts | where age > (25 + 5) | fields age ;
fetched rows / total rows = 3/3
+-------+
| age   |
|-------|
| 32    |
| 36    |
| 33    |
+-------+
```

**조건 연산자**  
조건 연산자는 true로 평가되는 표현식입니다. `MISSING` 및 `NULL` 값 비교는 다음 규칙을 따릅니다.
+ `MISSING` 값은 `MISSING` 값과만 같고 다른 값보다 작습니다.
+ `NULL` 값은 `NULL` 값과 같고 `MISSING` 값보다 크지만 다른 모든 값보다 작습니다.

**연산자**


**조건 연산자**  

| 이름 | 설명 | 
| --- | --- | 
| > | 보다 큼 연산자 | 
| >= | 크거나 같음 연산자 | 
| < | 보다 작음 연산자 | 
| \$1= | 같지 않은 연산자 | 
| <= | 작거나 같음 연산자 | 
| = | 같음 연산자 | 
| LIKE | 단순 패턴 일치 | 
| IN | NULL 값 테스트 | 
| AND | AND 연산자 | 
| OR | OR 연산자 | 
| XOR | XOR 연산자 | 
| NOT | NOT NULL 값 테스트 | 

날짜/시간을 비교할 수 있습니다. 서로 다른 날짜/시간 유형(예: `DATE` 및 `TIME`)을 비교할 때 둘 다 `DATETIME`으로 변환됩니다. 다음 규칙이 변환에 적용됩니다.
+  `TIME`은 오늘 날짜에 적용됩니다.
+ `DATE`는 자정에 해석됩니다.

**기본 조건 연산자**  
비교 연산자의 예:

```
os> source=accounts | where age > 33 | fields age ;
fetched rows / total rows = 1/1
+-------+
| age   |
|-------|
| 36    |
+-------+
```

**`IN`**  
값 목록의 `IN` 연산자 테스트 필드의 예:

```
os> source=accounts | where age in (32, 33) | fields age ;
fetched rows / total rows = 2/2
+-------+
| age   |
|-------|
| 32    |
| 33    |
+-------+
```

**`OR`**  
`OR` 연산자의 예:

```
os> source=accounts | where age = 32 OR age = 33 | fields age ;
fetched rows / total rows = 2/2
+-------+
| age   |
|-------|
| 32    |
| 33    |
+-------+
```

**`NOT`**  
`NOT` 연산자의 예:

```
os> source=accounts | where age not in (32, 33) | fields age ;
fetched rows / total rows = 2/2
+-------+
| age   |
|-------|
| 36    |
| 28    |
+-------+
```

##### PPL IP 주소 함수
<a name="supported-ppl-ip-address-functions"></a>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

##### `CIDRMATCH`
<a name="supported-ppl-address-functions-cidrmatch"></a>

**사용**: `CIDRMATCH(ip, cidr)`는 지정된 IP 주소가 지정된 cidr 범위 내에 있는지 확인합니다.

**인수 유형:**
+ STRING, STRING
+ 반환 유형: BOOLEAN

**예:**

```
os> source=ips | where cidrmatch(ip, '***********/24') | fields ip
fetched rows / total rows = 1/1
+--------------+
| ip           |
|--------------|
| ***********  |
+--------------+

os> source=ipsv6 | where cidrmatch(ip, '2003:db8::/32') | fields ip
fetched rows / total rows = 1/1
+-----------------------------------------+
| ip                                      |
|-----------------------------------------|
| 2003:0db8:****:****:****:****:****:0000 |
+-----------------------------------------+
```

**참고**  
`ip`는 IPv4 또는 IPv6 주소일 수 있습니다.
`cidr`은 IPv4 또는 IPv6 블록일 수 있습니다.
`ip` 및 `cidr`은 둘 다 IPv4이거나 둘 다 IPv6이어야 합니다.
`ip` 및 `cidr`은 모두 유효하고 비어 있지 않거나 null이 아니어야 합니다.

##### PPL JSON 함수
<a name="supported-ppl-json-functions"></a>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

##### `JSON`
<a name="supported-ppl-json-functions-json"></a>

**사용**: `json(value)`은 문자열을 JSON 형식으로 구문 분석할 수 있는지 여부를 평가합니다. 이 함수는 유효한 JSON인 경우 원래 문자열을 반환하고 유효하지 않은 경우 null을 반환합니다.

**인수 유형**: STRING

**반환 유형**: STRING/NULL. 유효한 JSON 객체 형식의 STRING 표현식입니다.

**예**:

```
os> source=people | eval `valid_json()` = json('[1,2,3,{"f1":1,"f2":[5,6]},4]') | fields valid_json
fetched rows / total rows = 1/1
+---------------------------------+
| valid_json                      |
+---------------------------------+
| [1,2,3,{"f1":1,"f2":[5,6]},4]   |
+---------------------------------+

os> source=people | eval `invalid_json()` = json('{"invalid": "json"') | fields invalid_json
fetched rows / total rows = 1/1
+----------------+
| invalid_json   |
+----------------+
| null           |
+----------------+
```

##### `JSON_OBJECT`
<a name="supported-ppl-json-functions-json-object"></a>

**사용**: `json_object(<key>, <value>[, <key>, <value>]...)`는 키-값 페어의 멤버에서 JSON 객체를 반환합니다.

**인수 유형:**
+ <key>는 문자열이어야 합니다.
+ <value>는 모든 데이터 형식일 수 있습니다.

**반환 유형**: JSON\$1OBJECT. 유효한 JSON 객체의 StructType 표현식입니다.

**예**:

```
os> source=people | eval result = json_object('key', 123.45) | fields result
fetched rows / total rows = 1/1
+------------------+
| result           |
+------------------+
| {"key":123.45}   |
+------------------+

os> source=people | eval result = json_object('outer', json_object('inner', 123.45)) | fields result
fetched rows / total rows = 1/1
+------------------------------+
| result                       |
+------------------------------+
| {"outer":{"inner":123.45}}   |
+------------------------------+
```

##### `JSON_ARRAY`
<a name="supported-ppl-json-functions-json-array"></a>

**사용**: `json_array(<value>...)`는 값 목록을 사용하여 JSON ARRAY를 생성합니다.

**인수 유형**: `<value>`는 문자열, 숫자 또는 부울과 같은 모든 종류의 값일 수 있습니다.

**반환 유형**: ARRAY. 유효한 JSON 배열에 대해 지원되는 모든 데이터 유형의 배열입니다.

**예**:

```
os> source=people | eval `json_array` = json_array(1, 2, 0, -1, 1.1, -0.11)
fetched rows / total rows = 1/1
+------------------------------+
| json_array                   |
+------------------------------+
| [1.0,2.0,0.0,-1.0,1.1,-0.11] |
+------------------------------+

os> source=people | eval `json_array_object` = json_object("array", json_array(1, 2, 0, -1, 1.1, -0.11))
fetched rows / total rows = 1/1
+----------------------------------------+
| json_array_object                      |
+----------------------------------------+
| {"array":[1.0,2.0,0.0,-1.0,1.1,-0.11]} |
+----------------------------------------+
```

##### `TO_JSON_STRING`
<a name="supported-ppl-json-functions-to-json-string"></a>

**사용**: `to_json_string(jsonObject)`은 지정된 json 객체 값을 가진 JSON 문자열을 반환합니다.

**인수 유형**: JSON\$1OBJECT 

**반환 유형**: STRING

**예**:

```
os> source=people | eval `json_string` = to_json_string(json_array(1, 2, 0, -1, 1.1, -0.11)) | fields json_string
fetched rows / total rows = 1/1
+--------------------------------+
| json_string                    |
+--------------------------------+
| [1.0,2.0,0.0,-1.0,1.1,-0.11]   |
+--------------------------------+

os> source=people | eval `json_string` = to_json_string(json_object('key', 123.45)) | fields json_string
fetched rows / total rows = 1/1
+-----------------+
| json_string     |
+-----------------+
| {'key', 123.45} |
+-----------------+
```

##### `ARRAY_LENGTH`
<a name="supported-ppl-json-functions-array-length"></a>

**사용**: `array_length(jsonArray)`는 가장 바깥쪽 배열에 속한 요소 수를 반환합니다.

**인수 유형**: ARRAY. ARRAY 또는 JSON\$1ARRAY 객체입니다.

**반환 유형**: INTEGER

**예:**

```
os> source=people | eval `json_array` = json_array_length(json_array(1,2,3,4)), `empty_array` = json_array_length(json_array())
fetched rows / total rows = 1/1
+--------------+---------------+
| json_array   | empty_array   |
+--------------+---------------+
| 4            | 0             |
+--------------+---------------+
```

##### `JSON_EXTRACT`
<a name="supported-ppl-json-functions-json-extract"></a>

**사용**: `json_extract(jsonStr, path)`는 지정된 JSON 경로를 기반으로 JSON 문자열에서 JSON 객체를 추출합니다. 입력 JSON 문자열이 유효하지 않은 경우 이 함수는 null을 반환합니다.

**인수 유형**: STRING, STRING

**반환 유형**: STRING
+ 유효한 JSON 객체 형식의 STRING 표현식입니다.
+ JSON이 잘못된 경우 `NULL`이 반환됩니다.

**예**:

```
os> source=people | eval `json_extract('{"a":"b"}', '$.a')` = json_extract('{"a":"b"}', '$a')
fetched rows / total rows = 1/1
+----------------------------------+
| json_extract('{"a":"b"}', 'a')   |
+----------------------------------+
| b                                |
+----------------------------------+

os> source=people | eval `json_extract('{"a":[{"b":1},{"b":2}]}', '$.a[1].b')` = json_extract('{"a":[{"b":1},{"b":2}]}', '$.a[1].b')
fetched rows / total rows = 1/1
+-----------------------------------------------------------+
| json_extract('{"a":[{"b":1.0},{"b":2.0}]}', '$.a[1].b')   |
+-----------------------------------------------------------+
| 2.0                                                       |
+-----------------------------------------------------------+

os> source=people | eval `json_extract('{"a":[{"b":1},{"b":2}]}', '$.a[*].b')` = json_extract('{"a":[{"b":1},{"b":2}]}', '$.a[*].b')
fetched rows / total rows = 1/1
+-----------------------------------------------------------+
| json_extract('{"a":[{"b":1.0},{"b":2.0}]}', '$.a[*].b')   |
+-----------------------------------------------------------+
| [1.0,2.0]                                                 |
+-----------------------------------------------------------+

os> source=people | eval `invalid_json` = json_extract('{"invalid": "json"')
fetched rows / total rows = 1/1
+----------------+
| invalid_json   |
+----------------+
| null           |
+----------------+
```

##### `JSON_KEYS`
<a name="supported-ppl-json-functions-json-keys"></a>

**사용**: `json_keys(jsonStr)`는 가장 바깥쪽 JSON 객체의 모든 키를 배열로 반환합니다.

**인수 유형**: STRING. 유효한 JSON 객체 형식의 STRING 표현식입니다.

**반환 유형**: ARRAY[STRING]. 이 함수는 다른 유효한 JSON 문자열, 빈 문자열 또는 잘못된 JSON에 대해 `NULL`을 반환합니다.

**예**:

```
os> source=people | eval `keys` = json_keys('{"f1":"abc","f2":{"f3":"a","f4":"b"}}')
fetched rows / total rows = 1/1
+------------+
| keus       |
+------------+
| [f1, f2]   |
+------------+

os> source=people | eval `keys` = json_keys('[1,2,3,{"f1":1,"f2":[5,6]},4]')
fetched rows / total rows = 1/1
+--------+
| keys   |
+--------+
| null   |
+--------+
```

##### `JSON_VALID`
<a name="supported-ppl-json-functions-json-valid"></a>

**사용**: `json_valid(jsonStr)`는 JSON 문자열이 유효한 JSON 구문을 사용하는지 여부를 평가하고 TRUE 또는 FALSE를 반환합니다.

**인수 유형**: STRING

**반환 유형**: BOOLEAN

**예**:

```
os> source=people | eval `valid_json` = json_valid('[1,2,3,4]'), `invalid_json` = json_valid('{"invalid": "json"') | feilds `valid_json`, `invalid_json`
fetched rows / total rows = 1/1
+--------------+----------------+
| valid_json   | invalid_json   |
+--------------+----------------+
| True         | False          |
+--------------+----------------+

os> source=accounts | where json_valid('[1,2,3,4]') and isnull(email) | fields account_number, email
fetched rows / total rows = 1/1
+------------------+---------+
| account_number   | email   |
|------------------+---------|
| 13               | null    |
+------------------+---------+
```

##### PPL Lambda 함수
<a name="supported-ppl-lambda-functions"></a>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

##### `EXISTS`
<a name="supported-ppl-lambda-functions-exists"></a>

**사용**: `exists(array, lambda)`는 Lambda 조건자가 배열의 하나 이상의 요소에 대해 보유하는지 여부를 평가합니다.

**인수 유형**: ARRAY, LAMBDA

**반환 유형**: BOOLEAN. 배열의 하나 이상의 요소가 Lambda 조건자를 충족하는 경우 `TRUE`를 반환하고, 그렇지 않으면 `FALSE`를 반환합니다.

**예**:

```
 os> source=people | eval array = json_array(1, -1, 2), result = exists(array, x -> x > 0) | fields result
fetched rows / total rows = 1/1
+-----------+
| result    |
+-----------+
| true      |
+-----------+

os> source=people | eval array = json_array(-1, -3, -2), result = exists(array, x -> x > 0) | fields result
fetched rows / total rows = 1/1
+-----------+
| result    |
+-----------+
| false     |
+-----------+
```

##### `FILTER`
<a name="supported-ppl-lambda-functions-filter"></a>

**사용량**: `filter(array, lambda)`는 지정된 Lambda 함수를 사용하여 입력 배열을 필터링합니다.

**인수 유형**: ARRAY, LAMBDA

**반환 유형**: ARRAY. Lambda 조건자를 충족하는 입력 배열의 모든 요소를 포함하는 ARRAY입니다.

**예**:

```
 os> source=people | eval array = json_array(1, -1, 2), result = filter(array, x -> x > 0) | fields result
fetched rows / total rows = 1/1
+-----------+
| result    |
+-----------+
| [1, 2]    |
+-----------+

os> source=people | eval array = json_array(-1, -3, -2), result = filter(array, x -> x > 0) | fields result
fetched rows / total rows = 1/1
+-----------+
| result    |
+-----------+
| []        |
+-----------+
```

##### `TRANSFORM`
<a name="supported-ppl-lambda-functions-transform"></a>

**사용**: `transform(array, lambda)`은 Lambda 변환 함수를 사용하여 배열의 요소를 변환합니다. 두 번째 인수는 바이너리 Lambda 함수를 사용하는 경우 요소의 인덱스를 의미합니다. 이는 기능 프로그래밍의 `map`과 유사합니다.

**인수 유형**: ARRAY, LAMBDA

**반환 유형**: ARRAY. 입력 배열의 각 요소에 Lambda 변환 함수를 적용한 결과가 포함된 ARRAY입니다.

**예**:

```
os> source=people | eval array = json_array(1, 2, 3), result = transform(array, x -> x + 1) | fields result
fetched rows / total rows = 1/1
+--------------+
| result       |
+--------------+
| [2, 3, 4]    |
+--------------+

os> source=people | eval array = json_array(1, 2, 3), result = transform(array, (x, i) -> x + i) | fields result
fetched rows / total rows = 1/1
+--------------+
| result       |
+--------------+
| [1, 3, 5]    |
+--------------+
```

##### `REDUCE`
<a name="supported-ppl-lambda-functions-reduce"></a>

**사용**: `reduce(array, start, merge_lambda, finish_lambda)`는 lambda 함수를 적용하여 배열을 단일 값으로 줄입니다. 함수는 merge\$1lambda를 시작 값과 모든 배열 요소에 적용한 다음 `finish_lambda`를 결과에 적용합니다.

**인수 유형**: ARRAY, ANY, LAMBDA, LAMBDA

**반환 유형**: ANY. Lambda 함수를 시작 값과 입력 배열에 적용한 최종 결과입니다.

**예**:

```
 os> source=people | eval array = json_array(1, 2, 3), result = reduce(array, 0, (acc, x) -> acc + x) | fields result
fetched rows / total rows = 1/1
+-----------+
| result    |
+-----------+
| 6         |
+-----------+

os> source=people | eval array = json_array(1, 2, 3), result = reduce(array, 10, (acc, x) -> acc + x) | fields result
fetched rows / total rows = 1/1
+-----------+
| result    |
+-----------+
| 16        |
+-----------+

os> source=people | eval array = json_array(1, 2, 3), result = reduce(array, 0, (acc, x) -> acc + x, acc -> acc * 10) | fields result
fetched rows / total rows = 1/1
+-----------+
| result    |
+-----------+
| 60        |
+-----------+
```

##### PPL 수학 함수
<a name="supported-ppl-math-functions"></a>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

##### `ABS`
<a name="supported-ppl-math-functions-abs"></a>

**사용**: `ABS(x) `는 x의 절대값을 계산합니다.

**인수 유형: **INTEGER/LONG/FLOAT/DOUBLE

**반환 유형:** INTEGER/LONG/FLOAT/DOUBLE

**예:**

```
os> source=people | eval `ABS(-1)` = ABS(-1) | fields `ABS(-1)`
fetched rows / total rows = 1/1
+-----------+
| ABS(-1)   |
|-----------|
| 1         |
+-----------+
```

##### `ACOS`
<a name="supported-ppl-math-functions-acos"></a>

**사용**: `ACOS(x)`는 x의 아크 코사인을 계산합니다. x가 -1\$11 범위에 속하지 않으면 `NULL`을 반환합니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형: **DOUBLE

**예:**

```
os> source=people | eval `ACOS(0)` = ACOS(0) | fields `ACOS(0)`
fetched rows / total rows = 1/1
+--------------------+
| ACOS(0)            |
|--------------------|
| 1.5707963267948966 |
+--------------------+
```

##### `ASIN`
<a name="supported-ppl-math-functions-asin"></a>

**사용**: `asin(x)`는 x의 아크 사인을 계산합니다. x가 -1\$11 범위에 속하지 않으면 `NULL`을 반환합니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형: **DOUBLE

**예:**

```
os> source=people | eval `ASIN(0)` = ASIN(0) | fields `ASIN(0)`
fetched rows / total rows = 1/1
+-----------+
| ASIN(0)   |
|-----------|
| 0.0       |
+-----------+
```

##### `ATAN`
<a name="supported-ppl-math-functions-atan"></a>

**사용**: `ATAN(x)`은 x의 아크 탄젠트를 계산합니다. `atan(y, x)`은 y/x의 아크 탄젠트를 계산합니다. 단, 두 인수의 기호에 따라 결과의 사분면이 결정됩니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형: **DOUBLE

**예:**

```
os> source=people | eval `ATAN(2)` = ATAN(2), `ATAN(2, 3)` = ATAN(2, 3) | fields `ATAN(2)`, `ATAN(2, 3)`
fetched rows / total rows = 1/1
+--------------------+--------------------+
| ATAN(2)            | ATAN(2, 3)         |
|--------------------+--------------------|
| 1.1071487177940904 | 0.5880026035475675 |
+--------------------+--------------------+
```

##### `ATAN2`
<a name="supported-ppl-math-functions-atan2"></a>

**사용**: `ATAN2(y, x)`는 y/x의 아크 탄젠트를 계산합니다. 단, 두 인수의 기호에 따라 결과의 사분면이 결정됩니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형: **DOUBLE

**예:**

```
os> source=people | eval `ATAN2(2, 3)` = ATAN2(2, 3) | fields `ATAN2(2, 3)`
fetched rows / total rows = 1/1
+--------------------+
| ATAN2(2, 3)        |
|--------------------|
| 0.5880026035475675 |
+--------------------+
```

##### `CBRT`
<a name="supported-ppl-math-functions-cbrt"></a>

**사용**: `CBRT`는 숫자의 세제곱근을 계산합니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형**: DOUBLE:

INTEGER/LONG/FLOAT/DOUBLE -> DOUBLE

**예:**

```
opensearchsql> source=location | eval `CBRT(8)` = CBRT(8), `CBRT(9.261)` = CBRT(9.261), `CBRT(-27)` = CBRT(-27) | fields `CBRT(8)`, `CBRT(9.261)`, `CBRT(-27)`;
fetched rows / total rows = 2/2
+-----------+---------------+-------------+
| CBRT(8)   | CBRT(9.261)   | CBRT(-27)   |
|-----------+---------------+-------------|
| 2.0       | 2.1           | -3.0        |
| 2.0       | 2.1           | -3.0        |
+-----------+---------------+-------------+
```

##### `CEIL`
<a name="supported-ppl-math-functions-ceil"></a>

**사용**: `CEILING` 함수의 별칭입니다. `CEILING(T)`은 값 T의 상한을 사용합니다.

**제한**: `CEILING`은 저장 시 IEEE 754 이중 유형이 십진수를 표시할 때만 예상대로 작동합니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형**: LONG

**예:**

```
os> source=people | eval `CEILING(0)` = CEILING(0), `CEILING(50.00005)` = CEILING(50.00005), `CEILING(-50.00005)` = CEILING(-50.00005) | fields `CEILING(0)`, `CEILING(50.00005)`, `CEILING(-50.00005)`
fetched rows / total rows = 1/1
+--------------+---------------------+----------------------+
| CEILING(0)   | CEILING(50.00005)   | CEILING(-50.00005)   |
|--------------+---------------------+----------------------|
| 0            | 51                  | -50                  |
+--------------+---------------------+----------------------+

os> source=people | eval `CEILING(3147483647.12345)` = CEILING(3147483647.12345), `CEILING(113147483647.12345)` = CEILING(113147483647.12345), `CEILING(3147483647.00001)` = CEILING(3147483647.00001) | fields `CEILING(3147483647.12345)`, `CEILING(113147483647.12345)`, `CEILING(3147483647.00001)`
fetched rows / total rows = 1/1
+-----------------------------+-------------------------------+-----------------------------+
| CEILING(3147483647.12345)   | CEILING(113147483647.12345)   | CEILING(3147483647.00001)   |
|-----------------------------+-------------------------------+-----------------------------|
| 3147483648                  | 113147483648                  | 3147483648                  |
+-----------------------------+-------------------------------+-----------------------------+
```

##### `CONV`
<a name="supported-ppl-math-functions-conv"></a>

**사용**: `CONV(x, a, b)`는 x를 a 진법에서 b 진법으로 변환합니다.

**인수 유형**: x: STRING, a: INTEGER, b: INTEGER

**반환 유형**: STRING

**예:**

```
os> source=people | eval `CONV('12', 10, 16)` = CONV('12', 10, 16), `CONV('2C', 16, 10)` = CONV('2C', 16, 10), `CONV(12, 10, 2)` = CONV(12, 10, 2), `CONV(1111, 2, 10)` = CONV(1111, 2, 10) | fields `CONV('12', 10, 16)`, `CONV('2C', 16, 10)`, `CONV(12, 10, 2)`, `CONV(1111, 2, 10)`
fetched rows / total rows = 1/1
+----------------------+----------------------+-------------------+---------------------+
| CONV('12', 10, 16)   | CONV('2C', 16, 10)   | CONV(12, 10, 2)   | CONV(1111, 2, 10)   |
|----------------------+----------------------+-------------------+---------------------|
| c                    | 44                   | 1100              | 15                  |
+----------------------+----------------------+-------------------+---------------------+
```

##### `COS`
<a name="supported-ppl-math-functions-cos"></a>

**사용**: `COS(x)`는 x의 코사인을 계산합니다. 여기서 x는 라디안 단위로 지정됩니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형: **DOUBLE

**예:**

```
os> source=people | eval `COS(0)` = COS(0) | fields `COS(0)`
fetched rows / total rows = 1/1
+----------+
| COS(0)   |
|----------|
| 1.0      |
+----------+
```

##### `COT`
<a name="supported-ppl-math-functions-cot"></a>

**사용**: `COT(x)`는 x의 코탄젠트를 계산합니다. x가 0과 같으면 out-of-range 오류가 반환됩니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형: **DOUBLE

**예:**

```
os> source=people | eval `COT(1)` = COT(1) | fields `COT(1)`
fetched rows / total rows = 1/1
+--------------------+
| COT(1)             |
|--------------------|
| 0.6420926159343306 |
+--------------------+
```

##### `CRC32`
<a name="supported-ppl-math-functions-crc32"></a>

**사용**: `CRC32`는 순환 중복 검사 값을 계산하고 부호 없는 32비트 값을 반환합니다.

**인수 유형**: STRING

**반환 유형**: LONG

**예:**

```
os> source=people | eval `CRC32('MySQL')` = CRC32('MySQL') | fields `CRC32('MySQL')`
fetched rows / total rows = 1/1
+------------------+
| CRC32('MySQL')   |
|------------------|
| 3259397556       |
+------------------+
```

##### `DEGREES`
<a name="supported-ppl-math-functions-degrees"></a>

**사용**: `DEGREES(x)`는 x를 라디안에서 도로 변환합니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형: **DOUBLE

**예:**

```
os> source=people | eval `DEGREES(1.57)` = DEGREES(1.57) | fields `DEGREES(1.57)`
fetched rows / total rows  = 1/1
+-------------------+
| DEGREES(1.57)     |
|-------------------|
| 89.95437383553924 |
+-------------------+
```

##### `E`
<a name="supported-ppl-math-functions-e"></a>

**사용**: `E()`는 오일러 수를 반환합니다.

**반환 유형**: DOUBLE

**예:**

```
os> source=people | eval `E()` = E() | fields `E()`
fetched rows / total rows = 1/1
+-------------------+
| E()               |
|-------------------|
| 2.718281828459045 |
+-------------------+
```

##### `EXP`
<a name="supported-ppl-math-functions-exp"></a>

**사용**: `EXP(x)`는 x의 출력으로 증가된 e를 반환합니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형: **DOUBLE

**예:**

```
os> source=people | eval `EXP(2)` = EXP(2) | fields `EXP(2)`
fetched rows / total rows = 1/1
+------------------+
| EXP(2)           |
|------------------|
| 7.38905609893065 |
+------------------+
```

##### `FLOOR`
<a name="supported-ppl-math-functions-floor"></a>

**사용**: `FLOOR(T)`는 값 T의 바닥값을 받습니다.

**제한**: `FLOOR`은 저장 시 IEEE 754 이중 유형이 십진수를 표시할 때만 예상대로 작동합니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형**: LONG

**예:**

```
os> source=people | eval `FLOOR(0)` = FLOOR(0), `FLOOR(50.00005)` = FLOOR(50.00005), `FLOOR(-50.00005)` = FLOOR(-50.00005) | fields `FLOOR(0)`, `FLOOR(50.00005)`, `FLOOR(-50.00005)`
fetched rows / total rows = 1/1
+------------+-------------------+--------------------+
| FLOOR(0)   | FLOOR(50.00005)   | FLOOR(-50.00005)   |
|------------+-------------------+--------------------|
| 0          | 50                | -51                |
+------------+-------------------+--------------------+

os> source=people | eval `FLOOR(3147483647.12345)` = FLOOR(3147483647.12345), `FLOOR(113147483647.12345)` = FLOOR(113147483647.12345), `FLOOR(3147483647.00001)` = FLOOR(3147483647.00001) | fields `FLOOR(3147483647.12345)`, `FLOOR(113147483647.12345)`, `FLOOR(3147483647.00001)`
fetched rows / total rows = 1/1
+---------------------------+-----------------------------+---------------------------+
| FLOOR(3147483647.12345)   | FLOOR(113147483647.12345)   | FLOOR(3147483647.00001)   |
|---------------------------+-----------------------------+---------------------------|
| 3147483647                | 113147483647                | 3147483647                |
+---------------------------+-----------------------------+---------------------------+

os> source=people | eval `FLOOR(282474973688888.022)` = FLOOR(282474973688888.022), `FLOOR(9223372036854775807.022)` = FLOOR(9223372036854775807.022), `FLOOR(9223372036854775807.0000001)` = FLOOR(9223372036854775807.0000001) | fields `FLOOR(282474973688888.022)`, `FLOOR(9223372036854775807.022)`, `FLOOR(9223372036854775807.0000001)`
fetched rows / total rows = 1/1
+------------------------------+----------------------------------+--------------------------------------+
| FLOOR(282474973688888.022)   | FLOOR(9223372036854775807.022)   | FLOOR(9223372036854775807.0000001)   |
|------------------------------+----------------------------------+--------------------------------------|
| 282474973688888              | 9223372036854775807              | 9223372036854775807                  |
+------------------------------+----------------------------------+--------------------------------------+
```

##### `LN`
<a name="supported-ppl-math-functions-ln"></a>

**사용**: `LN(x)`은 x의 자연 로그를 반환합니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형: **DOUBLE

**예:**

```
os> source=people | eval `LN(2)` = LN(2) | fields `LN(2)`
fetched rows / total rows = 1/1
+--------------------+
| LN(2)              |
|--------------------|
| 0.6931471805599453 |
+--------------------+
```

##### `LOG`
<a name="supported-ppl-math-functions-log"></a>

**사용**: `LOG(x)`는 x의 자연 로그, 즉 x의 기본 e 로그를 반환합니다. log(B, x)는 log(x)/log(B)와 동일합니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형: **DOUBLE

**예:**

```
os> source=people | eval `LOG(2)` = LOG(2), `LOG(2, 8)` = LOG(2, 8) | fields `LOG(2)`, `LOG(2, 8)`
fetched rows / total rows = 1/1
+--------------------+-------------+
| LOG(2)             | LOG(2, 8)   |
|--------------------+-------------|
| 0.6931471805599453 | 3.0         |
+--------------------+-------------+
```

##### `LOG2`
<a name="supported-ppl-math-functions-log2"></a>

**사용**: `LOG2(x)`는 `log(x)`/`log(2)`와 같습니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형: **DOUBLE

**예:**

```
os> source=people | eval `LOG2(8)` = LOG2(8) | fields `LOG2(8)`
fetched rows / total rows = 1/1
+-----------+
| LOG2(8)   |
|-----------|
| 3.0       |
+-----------+
```

##### `LOG10`
<a name="supported-ppl-math-functions-log10"></a>

**사용**: `LOG10(x)`는 `log(x)`/`log(10)`와 같습니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형: **DOUBLE

**예:**

```
os> source=people | eval `LOG10(100)` = LOG10(100) | fields `LOG10(100)`
fetched rows / total rows = 1/1
+--------------+
| LOG10(100)   |
|--------------|
| 2.0          |
+--------------+
```

##### `MOD`
<a name="supported-ppl-math-functions-mod"></a>

**사용**: `MOD(n, m)`는 숫자 n을 m으로 나눈 나머지를 계산합니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형**: m이 0 이외의 값인 경우 n과 m의 유형 중 더 넓은 유형입니다. m이 0인 경우는 NULL을 반환합니다.

**예:**

```
os> source=people | eval `MOD(3, 2)` = MOD(3, 2), `MOD(3.1, 2)` = MOD(3.1, 2) | fields `MOD(3, 2)`, `MOD(3.1, 2)`
fetched rows / total rows = 1/1
+-------------+---------------+
| MOD(3, 2)   | MOD(3.1, 2)   |
|-------------+---------------|
| 1           | 1.1           |
+-------------+---------------+
```

##### `PI`
<a name="supported-ppl-math-functions-pi"></a>

**사용**: `PI() `는 상수 pi를 반환합니다.

**반환 유형**: DOUBLE

**예:**

```
os> source=people | eval `PI()` = PI() | fields `PI()`
fetched rows / total rows = 1/1
+-------------------+
| PI()              |
|-------------------|
| 3.141592653589793 |
+-------------------+
```

##### `POW`
<a name="supported-ppl-math-functions-pow"></a>

**사용**: `POW(x, y)`는 x의 값을 y의 출력으로 계산합니다. 잘못된 입력은 `NULL` 결과를 반환합니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형**: DOUBLE

**동의어**: `POWER(_, _)`

**예:**

```
os> source=people | eval `POW(3, 2)` = POW(3, 2), `POW(-3, 2)` = POW(-3, 2), `POW(3, -2)` = POW(3, -2) | fields `POW(3, 2)`, `POW(-3, 2)`, `POW(3, -2)`
fetched rows / total rows = 1/1
+-------------+--------------+--------------------+
| POW(3, 2)   | POW(-3, 2)   | POW(3, -2)         |
|-------------+--------------+--------------------|
| 9.0         | 9.0          | 0.1111111111111111 |
+-------------+--------------+--------------------+
```

##### POWER
<a name="supported-ppl-math-functions-power"></a>

**사용**: `POWER(x, y)`는 x의 값을 y의 출력으로 계산합니다. 잘못된 입력은 `NULL` 결과를 반환합니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형**: DOUBLE

**동의어**: `POW(_, _)`

**예:**

```
os> source=people | eval `POWER(3, 2)` = POWER(3, 2), `POWER(-3, 2)` = POWER(-3, 2), `POWER(3, -2)` = POWER(3, -2) | fields `POWER(3, 2)`, `POWER(-3, 2)`, `POWER(3, -2)`
fetched rows / total rows = 1/1
+---------------+----------------+--------------------+
| POWER(3, 2)   | POWER(-3, 2)   | POWER(3, -2)       |
|---------------+----------------+--------------------|
| 9.0           | 9.0            | 0.1111111111111111 |
+---------------+----------------+--------------------+
```

##### `RADIANS`
<a name="supported-ppl-math-functions-radians"></a>

**사용**: `RADIANS(x)`는 x를 도에서 라디안으로 변환합니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형: **DOUBLE

**예:**

```
os> source=people | eval `RADIANS(90)` = RADIANS(90) | fields `RADIANS(90)`
fetched rows / total rows  = 1/1
+--------------------+
| RADIANS(90)        |
|--------------------|
| 1.5707963267948966 |
+--------------------+
```

##### `RAND`
<a name="supported-ppl-math-functions-rand"></a>

**사용**: `RAND()`/`RAND(N)`는 0 <= 값 < 1.0 범위의 임의의 부동 소수점 값을 반환합니다. 정수 N을 지정하면 함수가 실행 전에 시드를 초기화합니다. 이 동작의 한 가지 의미는 동일한 인수 N을 사용하면 `rand(N)`가 매번 동일한 값을 반환하여 반복 가능한 열 값 시퀀스를 생성한다는 것입니다.

**인수 유형**: INTEGER

**반환 유형**: FLOAT

**예:**

```
os> source=people | eval `RAND(3)` = RAND(3) | fields `RAND(3)`
fetched rows / total rows = 1/1
+------------+
| RAND(3)    |
|------------|
| 0.73105735 |
+------------+
```

##### `ROUND`
<a name="supported-ppl-math-functions-round"></a>

**사용량**: `ROUND(x, d)`는 인수 x를 소수점 이하 자릿수로 반올림합니다. d를 지정하지 않을 경우 기본값은 0입니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형 맵**:
+ (INTEGER/LONG [,INTEGER]) -> LONG
+ (FLOAT/DOUBLE [,INTEGER]) -> LONG

**예:**

```
os> source=people | eval `ROUND(12.34)` = ROUND(12.34), `ROUND(12.34, 1)` = ROUND(12.34, 1), `ROUND(12.34, -1)` = ROUND(12.34, -1), `ROUND(12, 1)` = ROUND(12, 1) | fields `ROUND(12.34)`, `ROUND(12.34, 1)`, `ROUND(12.34, -1)`, `ROUND(12, 1)`
fetched rows / total rows = 1/1
+----------------+-------------------+--------------------+----------------+
| ROUND(12.34)   | ROUND(12.34, 1)   | ROUND(12.34, -1)   | ROUND(12, 1)   |
|----------------+-------------------+--------------------+----------------|
| 12.0           | 12.3              | 10.0               | 12             |
+----------------+-------------------+--------------------+----------------+
```

##### `SIGN`
<a name="supported-ppl-math-functions-sign"></a>

**사용**: `SIGN`은 숫자가 음수, 0 또는 양수인지에 따라 인수의 부호를 -1, 0 또는 1로 반환합니다.

**인수 유형**: INTEGER/LONG/FLOAT/DOUBLE

**반환 유형:** INTEGER

**예:**

```
os> source=people | eval `SIGN(1)` = SIGN(1), `SIGN(0)` = SIGN(0), `SIGN(-1.1)` = SIGN(-1.1) | fields `SIGN(1)`, `SIGN(0)`, `SIGN(-1.1)`
fetched rows / total rows = 1/1
+-----------+-----------+--------------+
| SIGN(1)   | SIGN(0)   | SIGN(-1.1)   |
|-----------+-----------+--------------|
| 1         | 0         | -1           |
+-----------+-----------+--------------+
```

##### `SIN`
<a name="supported-ppl-math-functions-sin"></a>

**사용**: `sin(x)`은 x의 사인을 계산합니다. 여기서 x는 라디안 단위로 지정됩니다.

**인수 유형: **INTEGER/LONG/FLOAT/DOUBLE

**반환 유형: **DOUBLE

**예:**

```
os> source=people | eval `SIN(0)` = SIN(0) | fields `SIN(0)`
fetched rows / total rows = 1/1
+----------+
| SIN(0)   |
|----------|
| 0.0      |
+----------+
```

##### `SQRT`
<a name="supported-ppl-math-functions-sqrt"></a>

**사용**: `SQRT`는 음수가 아닌 숫자의 제곱근을 계산합니다.

**인수 유형: **INTEGER/LONG/FLOAT/DOUBLE

**반환 유형 맵:**
+ (음수가 아님) INTEGER/LONG/FLOAT/DOUBLE -> DOUBLE
+ (음수) INTEGER/LONG/FLOAT/DOUBLE -> NULL

**예:**

```
os> source=people | eval `SQRT(4)` = SQRT(4), `SQRT(4.41)` = SQRT(4.41) | fields `SQRT(4)`, `SQRT(4.41)`
fetched rows / total rows = 1/1
+-----------+--------------+
| SQRT(4)   | SQRT(4.41)   |
|-----------+--------------|
| 2.0       | 2.1          |
+-----------+--------------+
```

##### PPL 문자열 함수
<a name="supported-ppl-string-functions"></a>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

##### `CONCAT`
<a name="supported-ppl-string-functions-concat"></a>

**사용**: `CONCAT(str1, str2, ...., str_9)`는 최대 9개의 문자열을 하나로 더합니다.

**인수 유형:**
+ STRING, STRING, ...., STRING
+ 반환 유형: STRING

**예:**

```
os> source=people | eval `CONCAT('hello', 'world')` = CONCAT('hello', 'world'), `CONCAT('hello ', 'whole ', 'world', '!')` = CONCAT('hello ', 'whole ', 'world', '!') | fields `CONCAT('hello', 'world')`, `CONCAT('hello ', 'whole ', 'world', '!')`
fetched rows / total rows = 1/1
+----------------------------+--------------------------------------------+
| CONCAT('hello', 'world')   | CONCAT('hello ', 'whole ', 'world', '!')   |
|----------------------------+--------------------------------------------|
| helloworld                 | hello whole world!                         |
+----------------------------+--------------------------------------------+
```

##### `CONCAT_WS`
<a name="supported-ppl-string-functions-concat-ws"></a>

**사용**: `CONCAT_WS(sep, str1, str2)`는 지정된 구분 기호를 사용하여 두 개 이상의 문자열을 연결합니다.

**인수 유형:**
+ STRING, STRING, ...., STRING
+ 반환 유형: STRING

**예:**

```
os> source=people | eval `CONCAT_WS(',', 'hello', 'world')` = CONCAT_WS(',', 'hello', 'world') | fields `CONCAT_WS(',', 'hello', 'world')`
fetched rows / total rows = 1/1
+------------------------------------+
| CONCAT_WS(',', 'hello', 'world')   |
|------------------------------------|
| hello,world                        |
+------------------------------------+
```

##### `LENGTH`
<a name="supported-ppl-string-functions-length"></a>

**사용**: `length(str)`는 바이트 단위로 측정된 입력 문자열의 길이를 반환합니다.

**인수 유형:**
+ STRING
+ 반환 유형: INTEGER

**예:**

```
os> source=people | eval `LENGTH('helloworld')` = LENGTH('helloworld') | fields `LENGTH('helloworld')`
fetched rows / total rows = 1/1
+------------------------+
| LENGTH('helloworld')   |
|------------------------|
| 10                     |
+------------------------+
```

##### `LOWER`
<a name="supported-ppl-string-functions-lower"></a>

**사용**: `lower(string)`는 입력 문자열을 소문자로 변환합니다.

**인수 유형:**
+ STRING
+ 반환 유형: STRING

**예:**

```
os> source=people | eval `LOWER('helloworld')` = LOWER('helloworld'), `LOWER('HELLOWORLD')` = LOWER('HELLOWORLD') | fields `LOWER('helloworld')`, `LOWER('HELLOWORLD')`
fetched rows / total rows = 1/1
+-----------------------+-----------------------+
| LOWER('helloworld')   | LOWER('HELLOWORLD')   |
|-----------------------+-----------------------|
| helloworld            | helloworld            |
+-----------------------+-----------------------+
```

##### `LTRIM`
<a name="supported-ppl-string-functions-ltrim"></a>

**사용**: `ltrim(str)`은 입력 문자열에서 선행 공백 문자를 제거합니다

**인수 유형:**
+ STRING
+ 반환 유형: STRING

**예:**

```
os> source=people | eval `LTRIM('   hello')` = LTRIM('   hello'), `LTRIM('hello   ')` = LTRIM('hello   ') | fields `LTRIM('   hello')`, `LTRIM('hello   ')`
fetched rows / total rows = 1/1
+---------------------+---------------------+
| LTRIM('   hello')   | LTRIM('hello   ')   |
|---------------------+---------------------|
| hello               | hello               |
+---------------------+---------------------+
```

##### `POSITION`
<a name="supported-ppl-string-functions-position"></a>

**사용**: `POSITION(substr IN str)`은 문자열에서 하위 문자열이 처음 나타나는 위치를 반환합니다. 문자열에 하위 문자열이 없는 경우 0을 반환합니다. 인수가 NULL이면 NULL을 반환합니다.

**인수 유형:**
+ STRING, STRING
+ 반환 유형 INTEGER

**예:**

```
os> source=people | eval `POSITION('world' IN 'helloworld')` = POSITION('world' IN 'helloworld'), `POSITION('invalid' IN 'helloworld')`= POSITION('invalid' IN 'helloworld')  | fields `POSITION('world' IN 'helloworld')`, `POSITION('invalid' IN 'helloworld')`
fetched rows / total rows = 1/1
+-------------------------------------+---------------------------------------+
| POSITION('world' IN 'helloworld')   | POSITION('invalid' IN 'helloworld')   |
|-------------------------------------+---------------------------------------|
| 6                                   | 0                                     |
+-------------------------------------+---------------------------------------+
```

##### `REVERSE`
<a name="supported-ppl-string-functions-reverse"></a>

**사용**: `REVERSE(str)`는 입력 문자열의 반전된 문자열을 반환합니다.

**인수 유형:**
+ STRING
+ 반환 유형: STRING

**예:**

```
os> source=people | eval `REVERSE('abcde')` = REVERSE('abcde') | fields `REVERSE('abcde')`
fetched rows / total rows = 1/1
+--------------------+
| REVERSE('abcde')   |
|--------------------|
| edcba              |
+--------------------+
```

##### `RIGHT`
<a name="supported-ppl-string-functions-right"></a>

**사용**: `right(str, len)`는 입력 문자열에서 가장 오른쪽 문자를 반환합니다. 문자열에 하위 문자열이 없는 경우 0을 반환합니다. 인수가 NULL이면 NULL을 반환합니다.

**인수 유형:**
+ STRING, INTEGER
+ 반환 유형: STRING

**예:**

```
os> source=people | eval `RIGHT('helloworld', 5)` = RIGHT('helloworld', 5), `RIGHT('HELLOWORLD', 0)` = RIGHT('HELLOWORLD', 0) | fields `RIGHT('helloworld', 5)`, `RIGHT('HELLOWORLD', 0)`
fetched rows / total rows = 1/1
+--------------------------+--------------------------+
| RIGHT('helloworld', 5)   | RIGHT('HELLOWORLD', 0)   |
|--------------------------+--------------------------|
| world                    |                          |
+--------------------------+--------------------------+
```

##### `RTRIM`
<a name="supported-ppl-string-functions-rtrim"></a>

**사용**: `rtrim(str)`은 입력 문자열에서 후행 공백 문자를 자릅니다.

**인수 유형:**
+ STRING
+ 반환 유형: **STRING**

**예:**

```
os> source=people | eval `RTRIM('   hello')` = RTRIM('   hello'), `RTRIM('hello   ')` = RTRIM('hello   ') | fields `RTRIM('   hello')`, `RTRIM('hello   ')`
fetched rows / total rows = 1/1
+---------------------+---------------------+
| RTRIM('   hello')   | RTRIM('hello   ')   |
|---------------------+---------------------|
|    hello            | hello               |
+---------------------+---------------------+
```

##### `SUBSTRING`
<a name="supported-ppl-string-functions-substring"></a>

**사용**: `substring(str, start)` 또는 `substring(str, start, length)`은 입력 문자열의 하위 문자열을 반환합니다. 길이를 지정하지 않으면 시작 위치부터 전체 문자열을 반환합니다.

**인수 유형:**
+ STRING, INTEGER, INTEGER
+ 반환 유형: STRING

**예:**

```
os> source=people | eval `SUBSTRING('helloworld', 5)` = SUBSTRING('helloworld', 5), `SUBSTRING('helloworld', 5, 3)` = SUBSTRING('helloworld', 5, 3) | fields `SUBSTRING('helloworld', 5)`, `SUBSTRING('helloworld', 5, 3)`
fetched rows / total rows = 1/1
+------------------------------+---------------------------------+
| SUBSTRING('helloworld', 5)   | SUBSTRING('helloworld', 5, 3)   |
|------------------------------+---------------------------------|
| oworld                       | owo                             |
+------------------------------+---------------------------------+
```

##### `TRIM`
<a name="supported-ppl-string-functions-trim"></a>

**사용**: `trim(string)`은 입력 문자열에서 선행 및 후행 공백을 제거합니다.

**인수 유형:**
+ STRING
+ 반환 유형: **STRING**

**예:**

```
os> source=people | eval `TRIM('   hello')` = TRIM('   hello'), `TRIM('hello   ')` = TRIM('hello   ') | fields `TRIM('   hello')`, `TRIM('hello   ')`
fetched rows / total rows = 1/1
+--------------------+--------------------+
| TRIM('   hello')   | TRIM('hello   ')   |
|--------------------+--------------------|
| hello              | hello              |
+--------------------+--------------------+
```

##### `UPPER`
<a name="supported-ppl-string-functions-upper"></a>

**사용**: `upper(string)`는 문자열을 대문자로 변환합니다.

**인수 유형:**
+ STRING
+ 반환 유형: STRING

**예:**

```
os> source=people | eval `UPPER('helloworld')` = UPPER('helloworld'), `UPPER('HELLOWORLD')` = UPPER('HELLOWORLD') | fields `UPPER('helloworld')`, `UPPER('HELLOWORLD')`
fetched rows / total rows = 1/1
+-----------------------+-----------------------+
| UPPER('helloworld')   | UPPER('HELLOWORLD')   |
|-----------------------+-----------------------|
| HELLOWORLD            | HELLOWORLD            |
+-----------------------+-----------------------+
```

##### PPL 유형 변환 함수
<a name="supported-ppl-type-conversion-functions"></a>

**참고**  
이 PPL 함수를 지원하는 AWS 데이터 소스 통합을 확인하려면 섹션을 참조하세요[함수](#supported-ppl-functions).

##### `TRIM`
<a name="supported-ppl-conversion-functions-cast"></a>

**사용**: `cast(expr as dateType)`는 `expr`을 `dataType`으로 캐스팅하고 `dataType`의 값을 반환합니다.

다음 변환 규칙이 적용됩니다.


**유형 변환 규칙**  

| Src/Target | STRING | NUMBER | BOOLEAN | TIMESTAMP | DATE | TIME | 
| --- | --- | --- | --- | --- | --- | --- | 
| STRING |  | Note1 | Note1 | TIMESTAMP() | DATE() | TIME() | 
| NUMBER | Note1 |  | v\$1=0 | 해당 사항 없음 | 해당 사항 없음 | 해당 사항 없음 | 
| BOOLEAN | Note1 | v?1:0 |  | 해당 사항 없음 | 해당 사항 없음 | 해당 사항 없음 | 
| TIMESTAMP | Note1 | 해당 사항 없음 | 해당 사항 없음 |  | DATE() | TIME() | 
| DATE | Note1 | 해당 사항 없음 | 해당 사항 없음 | 해당 사항 없음 |  | 해당 사항 없음 | 
| TIME | Note1 | 해당 사항 없음 | 해당 사항 없음 | 해당 사항 없음 | 해당 사항 없음 |  | 

**문자열로 캐스팅 예:**

```
os> source=people | eval `cbool` = CAST(true as string), `cint` = CAST(1 as string), `cdate` = CAST(CAST('2012-08-07' as date) as string) | fields `cbool`, `cint`, `cdate`
fetched rows / total rows = 1/1
+---------+--------+------------+
| cbool   | cint   | cdate      |
|---------+--------+------------|
| true    | 1      | 2012-08-07 |
+---------+--------+------------+
```

**숫자로 캐스팅 예:**

```
os> source=people | eval `cbool` = CAST(true as int), `cstring` = CAST('1' as int) | fields `cbool`, `cstring`
fetched rows / total rows = 1/1
+---------+-----------+
| cbool   | cstring   |
|---------+-----------|
| 1       | 1         |
+---------+-----------+
```

**현재까지 캐스팅 예:**

```
os> source=people | eval `cdate` = CAST('2012-08-07' as date), `ctime` = CAST('01:01:01' as time), `ctimestamp` = CAST('2012-08-07 01:01:01' as timestamp) | fields `cdate`, `ctime`, `ctimestamp`
fetched rows / total rows = 1/1
+------------+----------+---------------------+
| cdate      | ctime    | ctimestamp          |
|------------+----------+---------------------|
| 2012-08-07 | 01:01:01 | 2012-08-07 01:01:01 |
+------------+----------+---------------------+
```

**체인 캐스팅 예:**

```
os> source=people | eval `cbool` = CAST(CAST(true as string) as boolean) | fields `cbool`
fetched rows / total rows = 1/1
+---------+
| cbool   |
|---------|
| True    |
+---------+
```