

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 支援的 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 中的資料。除了 Logs Insights QL 之外，CloudWatch Logs Insights Insights 也同時支援 OpenSearch PPL 和 OpenSearch SQL 查詢語言，這是用於分析 CloudWatch Logs 的專用查詢語言。
+ **OpenSearch SQL**：如果您習慣使用關聯式資料庫，OpenSearch SQL 會提供熟悉的選項。OpenSearch SQL 提供 SQL 功能的子集，使其成為執行臨機操作查詢和資料分析任務的理想選擇。使用 OpenSearch SQL，您可以使用 SELECT、 FROM、WHERE、GROUP BY、HAVING 等命令，以及 SQL 中可用的各種其他 SQL 命令和函數。您可以跨資料表 （或日誌群組） 執行 JOINs、使用子查詢關聯資料表 （或日誌群組） 的資料，並使用一組豐富的 JSON、數學、字串、條件式和其他 SQL 函數，對日誌和安全資料執行強大的分析。
+ **OpenSearch PPL (Piped Processing Language)：**使用 OpenSearch PPL，您可以使用管道互連命令擷取、查詢和分析資料，讓您更輕鬆地了解和編寫複雜的查詢。其語法是以 Unix 管道為基礎，並啟用命令鏈結來轉換和處理資料。使用 PPL，您可以篩選和彙總資料，並使用 JOINs、子查詢、 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>

下列參考表顯示 OpenSearch Discover 中支援哪些 SQL 命令來查詢 Amazon S3、Security Lake 或 CloudWatch Logs 中的資料，以及 CloudWatch Logs Insights 中支援哪些 SQL 命令。CloudWatch Logs Insights 和 OpenSearch Discover 中支援用於查詢 CloudWatch Logs 的 SQL 語法相同，並在下表中參考為 CloudWatch Logs。

**注意**  
OpenSearch 也支援 SQL 查詢在 OpenSearch 中擷取並存放在索引中的資料。此 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``


| 命令 | Description | CloudWatch Logs | Amazon S3 | Security Lake | 範例 命令 | 
| --- | --- | --- | --- | --- | --- | 
|  [SELECT 子句](#supported-sql-select)  |  顯示投影值。  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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) |  根據訂單子句中的欄位來排序結果。您可以依遞減或遞增順序排序。  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援 （必須使用 `Inner`和 `Left Outer`關鍵字才能聯結；SELECT 陳述式中僅支援一個 JOIN 操作）  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援 （必須使用內部、左側外部和跨關鍵字才能聯結） | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.svg) 不支援 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.svg) 不支援 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.svg) 不支援 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.svg) 不支援 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 與查詢中的 LIMIT 子句搭配使用時支援。例如：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/supported-directquery-sql.html) | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.svg) 不支援 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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) | 結合兩個或多個 SELECT 陳述式的結果 （例如 UNION、INTERSECT、EXCEPT)。 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.svg) 不支援 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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 Grammar | Description | CloudWatch Logs | Amazon S3 | Security Lake | 範例 命令 | 
| --- | --- | --- | --- | --- | --- | 
| [字串函數](#supported-sql-string) |  內建函數，可以操作和轉換 SQL 查詢中的字串和文字資料。例如，轉換案例、合併字串、擷取部分和清理文字。  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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) |  對多個資料列執行計算以產生單一摘要值的內建函數。例如，**總**和、**計數**、**平均值**、**最大值**和**最小值**。  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg)支援的 |  ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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) |  用於在 SQL 查詢中剖析、擷取、修改和查詢 JSON 格式資料的內建函數 （例如，from\$1json、to\$1json、get\$1json\$1object、json\$1tuple)，允許在資料集中操作 JSON 結構。  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.svg) 不支援 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.svg) 不支援 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 |  <pre>SELECT <br />    explode(array(10, 20)) </pre>  | 

## 一般 SQL 限制
<a name="general-sql-restrictions"></a>

將 OpenSearch SQL 與 CloudWatch Logs、Amazon S3 和 Security Lake 搭配使用時，適用下列限制。

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. 函數和表達式必須在欄位名稱上操作，並成為 SELECT 陳述式的一部分，其中包含 FROM 子句中指定的日誌群組。

   例如，不支援此查詢：

   ```
   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 個日誌群組。若要參考監控帳戶中的日誌群組，請使用 ARNs 而非`LogGroup`名稱。

查詢範例：

```
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)。 Amazon CloudWatch 限制包括您可以查詢的 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。


****  

| 函式 | Description | 
| --- | --- | 
| ascii(str) | 傳回 第一個字元的數值str。 | 
| base64(bin) | 將引數從二進位轉換為bin基本 64 字串。 | 
| bit\$1length(expr) | 傳回字串資料的位元長度或二進位資料的位元數。 | 
| btrim(str) | 從 移除開頭和結尾空格字元str。 | 
| btrim(str， trimStr) | 從 移除開頭和結尾trimStr字元str。 | 
| char(expr) | 傳回二進位等於 的 ASCII 字元expr。如果 n 大於 256，則結果等同於 chr(n % 256) | 
| char\$1length(expr) | 傳回字串資料的字元長度或二進位資料的位元組數。字串資料的長度包含結尾空格。二進位資料的長度包含二進位零。 | 
| character\$1length(expr) | 傳回字串資料的字元長度或二進位資料的位元組數。字串資料的長度包含結尾空格。二進位資料的長度包含二進位零。 | 
| chr(expr) | 傳回二進位等於 的 ASCII 字元expr。如果 n 大於 256，則結果等同於 chr(n % 256) | 
| concat\$1ws(sep【， str \$1 array(str)】＋) | 傳回以 分隔的字串串連sep，略過 null 值。 | 
| contains（左、右） | 傳回布林值。如果在左側找到右側，則值為 True。如果任一輸入表達式為 NULL，則傳回 NULL。否則， 會傳回 False。左側或右側都必須是 STRING 或 BINARY 類型。 | 
| decode(bin， 字元集） | 使用第二個引數字元集解碼第一個引數。 | 
| decode(expr， search， results 【， search， results 】 ... 【， default】) | 依序比較 expr 與每個搜尋值。如果 expr 等於搜尋值，解碼會傳回對應的結果。如果找不到相符項目，則會傳回預設值。如果省略預設值，則會傳回 null。 | 
| elt(n， input1， input2， ...) | 傳回 n-th 輸入，例如，當 n為 2 input2時傳回 。 | 
| encode(str， charset) | 使用第二個引數字元集編碼第一個引數。 | 
| endwith（左、右） | 傳回布林值。如果左結尾為右，則值為 True。如果任一輸入表達式為 NULL，則傳回 NULL。否則， 會傳回 False。左側或右側都必須是 STRING 或 BINARY 類型。 | 
| find\$1in\$1set(str， str\$1array) | 傳回逗號分隔清單 () 中指定字串 (str) 的索引 (1 型）str\$1array。如果找不到字串，或指定的字串 (str) 包含逗號，則傳回 0。 | 
| format\$1number(expr1， expr2) | 將數字格式化expr1為 '\$1，\$1\$1\$1，\$1\$1\$1.\$1\$1'，四捨五入為expr2小數位數。如果 expr2為 0，則結果沒有小數點或小數部分。 expr2也接受使用者指定的格式。這應該像 MySQL 的 FORMAT 一樣運作。 | 
| format\$1string(strfmt、obj、...) | 從 printf 格式格式字串傳回格式化字串。 | 
| initcap(str) | str 以大寫字母傳回每個單字的第一個字母。所有其他字母皆為小寫。字詞以空格分隔。 | 
| instr(str， substr) | 傳回 substr中第一次出現 的 (1 型） 索引str。 | 
| lcase(str) | 傳回 str ，並將所有字元變更為小寫。 | 
| left(str， len) | 從字串 傳回最左邊 len(len 可以是字串類型） 字元str，如果len小於或等於 0，則結果為空字串。 | 
| len(expr) | 傳回字串資料的字元長度或二進位資料的位元組數。字串資料的長度包含結尾空格。二進位資料的長度包含二進位零。 | 
| length(expr) | 傳回字串資料的字元長度或二進位資料的位元組數。字串資料的長度包含結尾空格。二進位資料的長度包含二進位零。 | 
| levenshtein(str1， str2【， threshold】) | 傳回兩個指定字串之間的 Levenshtein 距離。如果設定閾值且距離超過閾值，請傳回 -1。 | 
| locate(substr、str【、pos】) | 傳回位置 str之後第一次在 substr中出現的位置pos。指定值pos和傳回值是以 1 為基礎。 | 
| lower(str) | 傳回 str ，並將所有字元變更為小寫。 | 
| lpad(str， len【， pad】) | 傳回 str，以左填充，長度pad為 len。如果 str 超過 len，則傳回值會縮短為len字元或位元組。如果pad未指定 ，則如果是字元字串，str則會以空格字元填入左側，如果是位元組序列，則會以零填入。 | 
| ltrim(str) | 從 移除前置空格字元str。 | 
| luhn\$1check(str ) | 根據 Luhn 演算法檢查數字字串是否有效。此檢查總和函數廣泛套用至信用卡號碼和政府識別號碼，以區分有效號碼與輸入錯誤、不正確的號碼。 | 
| mask(input【， upperChar， lowerChar， digitChar， otherChar】) | 遮罩指定的字串值。函數會將字元取代為 'X' 或 'x'，並將數字取代為 'n'。這對於建立已移除敏感資訊的資料表複本很有用。 | 
| octet\$1length(expr) | 傳回字串資料的位元組長度或二進位資料的位元組數。 | 
| overlay（輸入、取代、pos【、len】) | input 以replace開頭為 pos且長度為 的 取代 len。 | 
| position(substr、str【、pos】) | 傳回位置 str之後第一次在 substr中出現的位置pos。指定值pos和傳回值是以 1 為基礎。 | 
| printf(strfmt、obj、...) | 從 printf 格式格式字串傳回格式化字串。 | 
| regexp\$1count(str， regexp) | 傳回字串 中規則表達式模式regexp相符的次數計數str。 | 
| regexp\$1extract(str、regexp【、idx】) | 在 中擷取str符合regexp表達式且對應至 regex 群組索引的第一個字串。 | 
| regexp\$1extract\$1all(str、regexp【、idx】) | 擷取 中str符合regexp表達式且對應至 regex 群組索引的所有字串。 | 
| regexp\$1instr(str， regexp) | 搜尋規則表達式的字串，並傳回整數，指出相符子字串的開始位置。位置是以 1 為基礎，而不是以 0 為基礎。如果找不到相符項目， 會傳回 0。 | 
| regexp\$1replace(str、regexp、rep【、 position】) | str 將相符的所有子字串取代regexp為 rep。 | 
| regexp\$1substr(str， regexp) | 傳回符合字串 regexp內規則表達式的子字串str。如果找不到規則表達式，則結果為 null。 | 
| repeat(str， n) | 傳回重複指定字串值 n 次的字串。 | 
| replace(str， search【， replace】) | search 以 取代 的所有出現次數replace。 | 
| right(str， len) | 從字串 傳回最右側的 len(len 可以是字串類型） 字元str，如果len小於或等於 0，則結果為空字串。 | 
| rpad(str， len【， pad】) | 傳回 str，以右填充，長度pad為 len。如果 str 超過 len，則傳回值會縮短為 len 個字元。如果pad未指定 ，則如果字元字串是空格字元，str則會在右側填入 ，如果是二進位字串，則會填入零。 | 
| rtrim(str) | 從 移除結尾空格字元str。 | 
| sentences(str【， lang， country】) | 分割str成單字陣列。 | 
| soundex(str) | 傳回字串的 Soundex 程式碼。 | 
| space(n) | 傳回由n空格組成的字串。 | 
| split(str、regex、 limit) | str 依符合的項目分割，regex並傳回長度上限為 的陣列 limit | 
| split\$1part(str， delimiter， partNum) | str 依分隔符號分割，並傳回請求的部分分割 (1 型）。如果任何輸入為 Null， 會傳回 Null。如果 partNum超出分割部分的範圍， 會傳回空字串。如果 partNum為 0， 會擲回錯誤。如果 partNum為負數，則部分會從字串結尾回溯計數。如果 delimiter是空字串，str則 不會分割。 | 
| startwith（左、右） | 傳回布林值。如果左開頭為右，則值為 True。如果任一輸入表達式為 NULL，則傳回 NULL。否則， 會傳回 False。左側或右側都必須是 STRING 或 BINARY 類型。 | 
| substr(str、pos【、len】) | 傳回str從 開始pos且長度為 的 子字串len，或從 pos開始且長度為 的位元組陣列配量len。 | 
| substr(str FROM pos【 FOR len】】) | 傳回str從 開始pos且長度為 的 子字串len，或從 pos開始且長度為 的位元組陣列配量len。 | 
| substring(str、pos【、len】) | 傳回str從 開始pos且長度為 的 子字串len，或從 pos開始且長度為 的位元組陣列配量len。 | 
| substring(str FROM pos【 FOR len】】) | 傳回str從 開始pos且長度為 的 子字串len，或從 pos開始且長度為 的位元組陣列配量len。 | 
| substring\$1index(str， delim， count) | 在count出現分隔符號 str之前，從 傳回子字串delim。如果 count 為正數，則會傳回最終分隔符號左側的所有項目 （從左側計數）。如果 count 為負數，則會傳回最終分隔符號右側的所有資料 （從右側計數）。函數 substring\$1index 會在搜尋 時執行區分大小寫的比對delim。 | 
| to\$1binary(str【， fmt】) | 根據提供的 str 將輸入轉換為二進位值fmt。 fmt可以是不區分大小寫的字串常值 "hex"、"utf-8"、"utf8" 或 "base64"。根據預設，如果fmt省略 ，則轉換的二進位格式為「十六」。如果至少一個輸入參數為 NULL，則函數會傳回 NULL。 | 
| to\$1char(numberExpr， formatExpr) | numberExpr 轉換為以 為基礎的字串formatExpr。如果轉換失敗，則擲回例外狀況。格式可以包含下列字元，不區分大小寫：'0' 或 '9'：指定介於 0 和 9 之間的預期數字。格式字串中的 0 或 9 序列符合輸入值中的數字序列，產生與格式字串中對應序列相同長度的結果字串。如果 0/9 序列包含的數字多於小數值的相符部分，開頭為 0，且位於小數點之前，則結果字串會加上零。否則，它會填充空格。 '.' 或 'D'：指定小數點的位置 （選用，只允許一次）。'，' 或 'G'：指定分組 （千） 分隔符號的位置 (，)。每個分組分隔符號的左側和右側必須有一個 0 或 9。 ' | 
| to\$1number(expr， fmt) | 將字串 'expr' 轉換為以字串格式 'fmt' 為基礎的數字。如果轉換失敗，則擲回例外狀況。格式可以包含下列字元，不區分大小寫：'0' 或 '9'：指定介於 0 和 9 之間的預期數字。格式字串中的 0 或 9 序列符合輸入字串中的數字序列。如果 0/9 序列以 0 開頭，且位於小數點之前，則只能比對相同大小的數字序列。否則，如果序列以 9 開頭或在小數點之後，它可以比對大小相同或更小的數字序列。 '.' 或 'D'：指定小數點的位置 （選用，只允許一次）。'，' 或 'G'：指定分組 （千） 分隔符號的位置 (，)。每個分組分隔符號的左側和右側必須有 0 或 9。'expr' 必須符合與數字大小相關的分組分隔符號。 ' | 
| to\$1varchar(numberExpr， formatExpr) | numberExpr 轉換為以 為基礎的字串formatExpr。如果轉換失敗，則擲回例外狀況。格式可以包含下列字元，不區分大小寫：'0' 或 '9'：指定介於 0 和 9 之間的預期數字。格式字串中的 0 或 9 序列符合輸入值中的數字序列，產生與格式字串中對應序列相同長度的結果字串。如果 0/9 序列包含的數字多於小數值的相符部分，開頭為 0，且位於小數點之前，則結果字串會加上零。否則，它會填充空格。 '.' 或 'D'：指定小數點的位置 （選用，只允許一次）。'，' 或 'G'：指定分組 （千） 分隔符號的位置 (，)。每個分組分隔符號的左側和右側必須有一個 0 或 9。 ' | 
| translate(input， from， to) | 將from字串中存在的字元取代為input字串中對應的字元，以翻譯to字串。 | 
| trim(str) | 從 移除開頭和結尾空格字元str。 | 
| trim（兩者都從 str) | 從 移除開頭和結尾空格字元str。 | 
| trim(LEADING FROM str) | 從 移除前置空格字元str。 | 
| trim(TRAILING FROM str) | 從 移除結尾空格字元str。 | 
| trim(trimStr FROM str) | 從 移除開頭和結尾trimStr字元str。 | 
| trim（兩個 trimStr FROM str) | 從 移除開頭和結尾trimStr字元str。 | 
| trim(LEADING trimStr FROM str) | 從 移除前置trimStr字元str。 | 
| trim(TRAILING trimStr FROM str) | 從 移除結尾trimStr字元str。 | 
| try\$1to\$1binary(str【， fmt】) | 這是to\$1binary執行相同操作的特殊 版本，但如果無法執行轉換，則傳回 NULL 值，而不是引發錯誤。 | 
| try\$1to\$1number(expr， fmt) | 將字串 'expr' 轉換為以字串格式 為基礎的數字fmt。如果字串 'expr' 不符合預期的格式，則傳回 NULL。格式遵循與 to\$1number 函數相同的語意。 | 
| ucase(str) | 傳回 str ，並將所有字元變更為大寫。 | 
| unbase64(str) | 將引數從基礎 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。


****  

| 函式 | Description | 
| --- | --- | 
| add\$1months(start\$1date、num\$1months) | 傳回 num\$1months之後的日期start\$1date。 | 
| convert\$1timezone(【sourceTz， 】targetTz， sourceTs) | 將不含時區的時間戳記sourceTs從sourceTz時區轉換為 targetTz。 | 
| curdate() | 傳回查詢評估開始時的目前日期。相同查詢內的所有 curdate 呼叫都會傳回相同的值。 | 
| current\$1date() | 傳回查詢評估開始時的目前日期。相同查詢中 current\$1date 的所有呼叫都會傳回相同的值。 | 
| current\$1date | 傳回查詢評估開始時的目前日期。 | 
| current\$1timestamp() | 傳回查詢評估開始時的目前時間戳記。相同查詢中 current\$1timestamp 的所有呼叫都會傳回相同的值。 | 
| current\$1timestamp | 傳回查詢評估開始時的目前時間戳記。 | 
| current\$1timezone() | 傳回目前的工作階段本機時區。 | 
| date\$1add(start\$1date， num\$1days) | 傳回 num\$1days之後的日期start\$1date。 | 
| date\$1diff(endDate， startDate) | 傳回從 startDate到 的天數endDate。 | 
| date\$1format（時間戳記，fmt) | timestamp 轉換為日期格式 所指定格式的字串值fmt。 | 
| date\$1from\$1unix\$1date（天） | 從 1970-01-01 開始的天數建立日期。 | 
| date\$1part（欄位，來源） | 擷取部分日期/時間戳記或間隔來源。 | 
| date\$1sub(start\$1date， num\$1days) | 傳回num\$1days早於 的日期start\$1date。 | 
| date\$1trunc(fmt， ts) | 傳回截斷至格式模型 ts 所指定單位的時間戳記fmt。 | 
| dateadd(start\$1date、num\$1days) | 傳回 num\$1days之後的日期start\$1date。 | 
| datediff(endDate， startDate) | 傳回從 startDate到 的天數endDate。 | 
| datepart（欄位，來源） | 擷取部分日期/時間戳記或間隔來源。 | 
| day（日期） | 傳回日期/時間戳記的月份日期。 | 
| dayofmonth（日期） | 傳回日期/時間戳記的月份日期。 | 
| dayofweek（日期） | 傳回日期/時間戳記的星期幾 (1 = 星期日，2 = 星期一，...，7 = 星期六）。 | 
| dayofyear（日期） | 傳回日期/時間戳記的年份日期。 | 
| extract（欄位 FROM 來源） | 擷取部分日期/時間戳記或間隔來源。 | 
| from\$1unixtime(unix\$1time【， fmt】) | 在指定的 unix\$1time中傳回 fmt。 | 
| from\$1utc\$1timestamp（時間戳記，時區） | 假設時間戳記如 '2017-07-14 02：40：00.0'， 會以 UTC 將其解譯為時間，並在指定時區將該時間轉譯為時間戳記。例如，「GMT\$11」會產生「2017-07-14 03：40：00.0」。 | 
| hour（時間戳記） | 傳回字串/時間戳記的小時元件。 | 
| last\$1day（日期） | 傳回日期所屬月份的最後一天。 | 
| localtimestamp() | 在查詢評估開始時，傳回不含時區的目前時間戳記。相同查詢內的所有當地時間戳記呼叫都會傳回相同的值。 | 
| localtimestamp | 在查詢評估開始時，傳回工作階段時區的目前本機日期時間。 | 
| make\$1date（年、月、日） | 建立年份、月份和日期欄位的日期。 | 
| make\$1dt\$1interval(【days【， hours【， mins【， secs】】】】) | 從天、小時、分鐘和秒建立 DayTimeIntervalType 持續時間。 | 
| make\$1interval(【years【， months【， weeks【， days【， hours【， mins【， secs】】】】】】】】】) | 間隔數年、月、週、日、小時、分鐘和秒。 | 
| make\$1timestamp（年、月、日、小時、分鐘、秒【、時區】) | 從年、月、日、小時、分鐘、秒和時區欄位建立時間戳記。 | 
| make\$1timestamp\$1ltz（年、月、日、小時、分鐘、秒【、時區】) | 使用從年、月、日、小時、分鐘、秒和時區欄位的當地時區建立目前的時間戳記。 | 
| make\$1timestamp\$1ntz（年、月、日、小時、分鐘、秒） | 從年、月、日、小時、分鐘、秒欄位建立本機日期時間。 | 
| make\$1ym\$1interval(【年【，月】】) | 以年、月為間隔。 | 
| minute（時間戳記） | 傳回字串/時間戳記的分鐘元件。 | 
| month(date) | 傳回日期/時間戳記的月份元件。 | 
| months\$1between(timestamp1， timestamp2【， roundOff】) | 如果 timestamp1 晚於 timestamp2，則結果為正值。如果 timestamp1和 timestamp2 在當月的同一天，或兩者都是當月的最後一天，則會忽略時間。否則，差異會根據每月 31 天計算，並四捨五入至 8 位數，除非 roundOff=false。 | 
| next\$1day(start\$1date， day\$1of\$1week) | 傳回第一個晚於 start\$1date並依指示命名的日期。如果至少一個輸入參數是 NULL，則函數會傳回 NULL。 | 
| now() | 傳回查詢評估開始時的目前時間戳記。 | 
| quarter（日期） | 傳回日期的年份季度，範圍為 1 到 4。 | 
| second（時間戳記） | 傳回字串/時間戳記的第二個元件。 | 
| session\$1window(time\$1column， gap\$1duration) | 根據指定資料欄和間隙持續時間的時間戳記產生工作階段視窗。如需詳細說明和範例，請參閱結構化串流指南文件中的「時段類型」。 | 
| timestamp\$1micros（微秒） | 從 UTC epoch 後的微秒數建立時間戳記。 | 
| timestamp\$1millis（毫秒） | 從 UTC epoch 後的毫秒數建立時間戳記。 | 
| timestamp\$1seconds（秒） | 從 UTC epoch 後的秒數 （可以是小數） 建立時間戳記。 | 
| 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（時間戳記，時區） | 假設時間戳記如 '2017-07-14 02：40：00.0'， 會將其解譯為指定時區中的時間，並將該時間轉譯為 UTC 中的時間戳記。例如，「GMT\$11」會產生「2017-07-14 01：40：00.0」。 | 
| trunc(date， fmt) | 傳回 ，date並將一天中的時間部分截斷為格式模型 指定的單位fmt。 | 
| try\$1to\$1timestamp(timestamp\$1str【， fmt】) | 將timestamp\$1str表達式與fmt表達式剖析為時間戳記。 | 
| unix\$1date(date) | 傳回自 1970-01-01 起的天數。 | 
| unix\$1micros（時間戳記） | 傳回自 1970-01-01 00：00：00 UTC 以來的微秒數。 | 
| unix\$1millis（時間戳記） | 傳回自 1970-01-01 00：00：00 UTC 以來的毫秒數。截斷更高層級的精確度。 | 
| unix\$1seconds（時間戳記） | 傳回自 1970-01-01 00：00：00 UTC 以來的秒數。截斷更高層級的精確度。 | 
| unix\$1timestamp(【timeExp【， fmt】】) | 傳回目前或指定時間的 UNIX 時間戳記。 | 
| weekday（日期） | 傳回日期/時間戳記的星期幾 (0 = 星期一，1 = 星期二，...，6 = 星期日）。 | 
| weekofyear（日期） | 傳回指定日期當年的一週。一週被視為從星期一開始，而第 1 週是 >3 天的第一週。 | 
| window(time\$1column， window\$1duration【， slide\$1duration【， start\$1time】】) | 使用時間戳記指定資料欄，將資料列歸納到一或多個時段。視窗開始包含 ，但視窗結束是排他性的，例如 12：05 將位於視窗 【12：05，12：10) 中，但不會在 【12：00，12：05) 中。Windows 可支援微秒精確度。不支援按月順序排列的 Windows。如需詳細說明和範例，請參閱結構化串流指南文件中的「事件時間視窗操作」。 | 
| window\$1time(window\$1column) | 從時間/工作階段視窗資料欄擷取時間值，可用於視窗的事件時間值。擷取的時間是 (window.end - 1)，反映彙總視窗具有專屬上限 - 【開始、結束） 的事實。如需詳細說明和範例，請參閱結構化串流指南文件中的「事件時間視窗操作」。 | 
| year（日期） | 傳回日期/時間戳記的年份元件。 | 

**範例**

```
-- 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。


****  

| 函式 | Description | 
| --- | --- | 
| coalesce(expr1、expr2、...) | 如果存在，則傳回第一個非 Null 引數。否則為 null。 | 
| if(expr1、expr2、expr3) | 如果 expr1評估為 true，則傳回 expr2；否則傳回 expr3。 | 
| ifnull(expr1， expr2) | expr2 如果 expr1為 null expr1或其他，則傳回 。 | 
| nanvl(expr1， expr2) | expr1 如果不是 NaN，expr2否則傳回 。 | 
| nullif(expr1， expr2) | 如果 expr1 等於 expr2，expr1否則傳回 null。 | 
| nvl(expr1， expr2) | expr2 如果 expr1為 null expr1或其他，則傳回 。 | 
| nvl2(expr1、expr2、expr3) | expr2 如果 expr1 不是 null，則傳回 ，expr3否則傳回 。 | 
| expr1 和 expr2 【當 expr3 和 expr4】\$1 【ELSE expr5】 結束時的案例 | 當 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。




****  

| 函式 | Description | 
| --- | --- | 
| from\$1json(jsonStr， schema【， options】) | 傳回具有指定 `jsonStr` 和 `schema` 的結構值。 | 
| get\$1json\$1object(json\$1txt， 路徑） | 從 `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【， 選項】) | 以 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。


****  

| 函式 | Description | 
| --- | --- | 
| array(expr， ...) | 傳回具有指定元素的陣列。 | 
| array\$1append(array， 元素） | 在傳遞為第一個引數的陣列結尾新增 元素。元素類型應類似於陣列的元素類型。Null 元素也會附加到陣列中。但是，如果傳遞陣列，則 NULL 輸出為 NULL | 
| array\$1compact(array) | 從陣列中移除 null 值。 | 
| array\$1contains（陣列，值） | 如果陣列包含 值，則傳回 true。 | 
| array\$1distinct(array) | 從陣列中移除重複的值。 | 
| array\$1except(array1， array2) | 傳回 array1 中的元素陣列，但不傳回 array2 中的元素陣列，無需重複。 | 
| array\$1insert(x， pos， val) | 將 val 放入陣列 x 的索引位置。陣列索引從 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， 元素） | 傳回陣列中第一個相符元素的 (1 型） 索引長度，如果找不到相符項目，則傳回 0。 | 
| array\$1prepend(array， 元素） | 在傳遞為第一個引數的陣列開頭新增 元素。元素類型應與陣列的元素類型相同。Null 元素也會在陣列前面。但是，如果傳遞的陣列是 NULL 輸出是 NULL | 
| array\$1remove(array， 元素） | 從陣列中移除所有等於 元素的元素。 | 
| array\$1repeat(element， count) | 傳回包含元素計數時間的陣列。 | 
| array\$1union(array1， array2) | 傳回 array1 和 array2 聯集的元素陣列，無需重複。 | 
| arrays\$1overlap(a1， a2) | 如果 a1 至少包含 a2 中也存在的非空元素，則傳回 true。如果陣列沒有常見元素，而且兩者都是非空的，且其中之一包含 null 元素，則會傳回 false。 | 
| arrays\$1zip(a1、a2、...) | 傳回合併的結構陣列，其中 N 個結構包含輸入陣列的所有 N 個值。 | 
| flatten(arrayOfArrays) | 將陣列轉換為單一陣列。 | 
| get（陣列，索引） | 傳回指定 (0 型） 索引的陣列元素。如果索引指向陣列邊界之外，則此函數會傳回 NULL。 | 
| sequence（開始、停止、步驟） | 產生從開始到停止 （包含） 的元素陣列，依步驟遞增。傳回的元素類型與引數表達式類型相同。支援的類型為：位元組、短、整數、長、日期、時間戳記。開始和停止表達式必須解析為相同類型。如果開始和停止表達式解析為 'date' 或 'timestamp' 類型，則步驟表達式必須解析為 'interval' 或 'year-month interval' 或 'day-time interval' 類型，否則解析為與開始和停止表達式相同的類型。 | 
| shuffle(array) | 傳回指定陣列的隨機排列。 | 
| slice(x， start， length) | 子集陣列 x 從索引開頭開始 （陣列索引從 1 開始，如果開頭為負值，則從結尾開始），並指定長度。 | 
| 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。

視窗函數在一組資料列上運作，稱為視窗，並根據資料列群組計算每一列的傳回值。視窗函數適用於處理任務，例如計算移動平均值、計算累積統計資料，或存取指定目前資料列相對位置的資料列值。

**語法** 

```
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` - 指定在評估視窗函數時是否略過 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 `

  位移：指定與目前資料列位置的位移。

  **注意** 如果省略 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。


****  

| 函式 | Description | 
| --- | --- | 
| bigint(expr) | 將值 `expr` 轉換為目標資料類型 `bigint`。 | 
| binary(expr) | 將值 `expr` 轉換為目標資料類型 `binary`。 | 
| 布林值 (expr) | 將值 `expr` 轉換為目標資料類型 `boolean`。 | 
| cast(expr AS 類型） | 將值 `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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。


****  

| 函式 | Description | 
| --- | --- | 
| ！ expr | 邏輯非。 | 
| expr1 < expr2 | 如果 `expr1` 小於 `expr2`，則傳回 true。 | 
| expr1 <= expr2 | 如果 `expr1` 小於或等於 `expr2`，則傳回 true。 | 
| expr1 <=> expr2 | 傳回與非 Null 運算元的 EQUAL(=) 運算子相同的結果，但如果兩者皆為 Null，則傳回 true，如果其中之一為 Null，則傳回 false。 | 
| expr1 = expr2 | 如果 `expr1` 等於 `expr2`，否則傳回 true。 | 
| expr1 == expr2 | 如果 `expr1` 等於 `expr2`，否則傳回 true。 | 
| expr1 > expr2 | 如果 `expr1` 大於 `expr2`，則傳回 true。 | 
| expr1 >= expr2 | 如果 `expr1` 大於或等於 `expr2`，則傳回 true。 | 
| expr1 和 expr2 | 邏輯 AND。 | 
| str ilike 模式【 ESCAPE 逸出】 | 如果 str 符合 `pattern` 與 `escape` 不區分大小寫，則傳回 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 模式【 ESCAPE 逸出】 | 如果 str 符合 `pattern` 與 `escape`，則傳回 true；如果任何引數為 null，則傳回 null；否則傳回 false。 | 
| 非 expr | 邏輯非。 | 
| expr1 或 expr2 | 邏輯 OR。 | 
| regexp(str， regexp) | 如果 `str` 符合 `regexp`，否則傳回 true。 | 
| regexp\$1like(str， regexp) | 如果 `str` 符合 `regexp`，否則傳回 true。 | 
| rlike(str， regexp) | 如果 `str` 符合 `regexp`，否則傳回 true。 | 

**範例**

```
-- !
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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。


****  

| 函式 | Description | 
| --- | --- | 
| element\$1at(array，索引） | 傳回指定 (1 型） 索引的陣列元素。 | 
| element\$1at（映射，索引鍵） | 傳回指定金鑰的值。如果地圖中不包含金鑰，則函數會傳回 NULL。 | 
| map(key0， value0， key1， value1， ...) | 使用指定的鍵/值對建立映射。 | 
| map\$1concat(map， ...) | 傳回所有指定映射的聯集 | 
| map\$1contains\$1key（地圖，金鑰） | 如果映射包含 金鑰，則傳回 true。 | 
| map\$1entries(map) | 傳回指定映射中所有項目的未排序陣列。 | 
| map\$1from\$1arrays（索引鍵、值） | 使用一對指定的索引鍵/值陣列建立映射。金鑰中的所有元素不應為 null | 
| map\$1from\$1entries(arrayOfEntries) | 傳回從指定項目陣列建立的映射。 | 
| map\$1keys（地圖） | 傳回未排序的陣列，其中包含映射的索引鍵。 | 
| map\$1values(map) | 傳回未排序的陣列，其中包含映射的值。 | 
| str\$1to\$1map(text【， pairDelim【， keyValueDelim】】) | 使用分隔符號將文字分割為鍵/值對後建立映射。`pairDelim` 的預設分隔符號為 '，'，`keyValueDelim` 的預設分隔符號為 '：'。`pairDelim` 和 `keyValueDelim` 都視為規則表達式。 | 
| try\$1element\$1at(array，索引） | 傳回指定 (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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。


****  

| 函式 | Description | 
| --- | --- | 
| 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) | 傳回 `expr` 的反餘弦 (a.k.a. arc cosine)，就像由 `java.lang.Math.acos` 運算一樣。 | 
| acosh(expr) | 傳回 `expr` 的反雙曲餘弦。 | 
| asin(expr) | 傳回 `expr` 的反正弦 (a.k.a. arc 正弦） arc sin，就像由 `java.lang.Math.asin` 計算一樣。 | 
| asinh(expr) | 傳回 `expr` 的反雙曲正弦。 | 
| atan(expr) | 傳回 `expr` 的反正切 (a.k.a. arc tangent)，就像由 `java.lang.Math.atan` 運算一樣 | 
| atan2(exprY， exprX) | 傳回平面正 x 軸與座標 (`exprX`、`exprY`) 給定點之間的弧度角度，就像由 `java.lang.Math.atan2` 計算一樣。 | 
| atanh(expr) | 傳回 `expr` 的反雙曲切線。 | 
| bin(expr) | 傳回以二進位表示的長值 `expr` 的字串表示。 | 
| bround(expr， d) | 使用 HALF\$1EVEN 四捨五入模式，傳回四捨五入至小數位數 `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) | 傳回 `expr` 的餘弦，就像由 `java.lang.Math.cos` 運算一樣。 | 
| cosh(expr) | 傳回 `expr` 的雙曲餘弦，就像由 `java.lang.Math.cosh` 計算一樣。 | 
| cot(expr) | 傳回 `expr` 的餘切，就像由 `1/java.lang.Math.tan` 計算一樣。 | 
| csc(expr) | 傳回 `expr` 的餘數，就像由 `1/java.lang.Math.sin` 計算一樣。 | 
| degrees(expr) | 將弧度轉換為度數。 | 
| expr1 div expr2 | 將 `expr1` 除以 `expr2`。如果運算元為 NULL 或 `expr2` 為 0，則傳回 NULL。結果會轉換為長。 | 
| 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` 轉換為十六進位。 | 
| 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 四捨五入模式，傳回四捨五入至小數位數 `expr`。 | 
| sec(expr) | 傳回 `expr` 的正負數，就像由 `1/java.lang.Math.cos` 計算一樣。 | 
| shiftleft（基礎、expr) | 位元向左移位。 | 
| sign(expr) | 傳回 -1.0、0.0 或 1.0，因為 `expr` 為負數、0 或正數。 | 
| signum(expr) | 傳回 -1.0、0.0 或 1.0，因為 `expr` 為負數、0 或正數。 | 
| sin(expr) | 傳回 `expr` 的正弦，就像由 `java.lang.Math.sin` 計算一樣。 | 
| sinh(expr) | 傳回 `expr` 的雙曲正弦，就像由 `java.lang.Math.sinh` 運算一樣。 | 
| sqrt(expr) | 傳回 `expr` 的平方根。 | 
| tan(expr) | 傳回 `expr` 的正切，就像由 `java.lang.Math.tan` 計算一樣。 | 
| tanh(expr) | 傳回 `expr` 的雙曲正切，就像由 `java.lang.Math.tanh` 計算一樣。 | 
| 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) | 將十六進位 `expr` 轉換為二進位。 | 
| width\$1bucket(value、min\$1value、max\$1value、num\$1bucket) | 傳回 `value` 將在具有 `num\$1bucket` 儲存貯體的等寬長條圖中指派給的儲存貯體編號，範圍為 `min\$1value` 到 `max\$1value`。」 | 

**範例**

```
-- %
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>

**注意**  
若要查看哪些 AWS 資料來源整合支援這些 SQL 函數，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。


****  

| 函式 | Description | 
| --- | --- | 
| 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 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 ]
```

 **參數** 
+ **ALL** 

  從關係中選取所有相符的資料列，並預設為啟用。
+ **DISTINCT** 

  在移除結果中的重複項目後，從關係中選取所有相符的資料列。
+ **named\$1expression **

  具有指派名稱的表達式。一般而言，它會表示資料欄表達式。

  語法: `expression [[AS] alias]` 
+ **from\$1item **

  資料表關聯

  聯結關係

  樞紐關係

  取消樞紐關係

  資料表值函數

  內嵌資料表

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

  `PIVOT` 子句用於資料觀點。您可以根據特定資料欄值取得彙總值。
+ **UNPIVOT** 

  `UNPIVOT` 子句會將資料欄轉換為資料列。這是 的反向`PIVOT`，但值的彙總除外。
+ **橫向檢視 **

  `LATERAL VIEW` 子句會與 等產生器函數搭配使用`EXPLODE`，這會產生包含一或多個資料列的虛擬資料表。

  `LATERAL VIEW` 會將資料列套用至每個原始輸出資料列。
+ **WHERE** 

  根據提供的述詞篩選 `FROM`子句的結果。
+ **GROUP BY **

  指定用於分組資料列的表達式。

  這與彙總函數 (`MIN`、`MAX`、`AVG`、、 `COUNT` `SUM`等） 搭配使用，以根據每個群組中的分組表達式和彙總值來分組資料列。

  當子`FILTER`句連接到彙總函數時，只有相符的資料列會傳遞至該函數。
+ **哈維** 

  指定 產生的資料列`GROUP BY`篩選依據的述詞。

  子`HAVING`句用於在執行分組後篩選資料列。

  如果指定的 `HAVING` 沒有 `GROUP BY`，則表示 `GROUP BY`沒有分組表達式 （全域彙總）。
+ **ORDER BY **

  指定查詢完整結果集的資料列順序。

  輸出列會依分割區排序。

  此參數與 `DISTRIBUTE BY` `SORT BY`和 互斥，無法同時指定。
+ **SORT BY **

  指定列在每個分割區中排序的順序。

  此參數與 互斥`ORDER BY`，無法同時指定。
+ **LIMIT** 

  指定陳述式或子查詢可傳回的資料列數目上限。

  此子句主要與 搭配使用`ORDER BY`，以產生決定性結果。
+ **boolean\$1expression **

  指定評估為結果類型布林值的任何表達式。

  兩個或多個表達式可以使用邏輯運算子 (`AND`、) 結合在一起`OR`。
+ **表達式** 

  指定評估為值的一或多個值、運算子和 SQL 函數的組合。
+ **named\$1window **

  指定一或多個來源視窗規格的別名。

  您可以在查詢的精靈定義中參考來源視窗規格。

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

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 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 **

  分組集由括號中的零或多個逗號分隔表達式指定。當分組集只有一個元素時，可以省略括號。

  例如，`GROUPING SETS ((a), (b))` 與 `GROUPING SETS (a, b)` 相同。

  語法: `{ ( [ expression [ , ... ] ] ) | expression }` 
+ **分組集 **

  將 之後指定的每個分組集的資料列分組`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`也可以具有巢狀`CUBE|ROLLUP|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`。 `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`、`AVG`、、 `COUNT` `SUM`等）。
+ **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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 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，則先`NULLs`排序，如果排序順序為 ，則先排序；如果排序順序為 ，則先排序 `ASC` NULLS 排序`DESC`。

  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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。

SQL 聯結用於根據聯結條件結合來自兩個關係的資料列。下一節說明整體聯結語法，以及不同類型的聯結以及範例。

**語法** 

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

**參數**
+ **關係 **

  指定要加入的關係。
+ **join\$1type **

  指定聯結類型。

  語法: `INNER | CROSS | LEFT OUTER`
+ **join\$1criteria **

  指定來自一個關係的資料列將如何與另一個關係的資料列合併。

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

  指定傳回類型為布林值的表達式。

**聯結類型**
+ **內部聯結**

  內部聯結需要明確指定。它會選取在兩個關係中具有相符值的資料列。

  語法: `relation INNER JOIN relation [ join_criteria ] `
+ **左聯結 **

  左聯結會傳回來自左關係的所有值，以及來自右關係的相符值，或者如果沒有相符項目，則附加 NULL。它也稱為左側外部聯結。

  語法: `relation LEFT OUTER JOIN relation [ join_criteria ]` 
+ **交叉聯結 **

  交叉聯結會傳回兩個關係的笛卡爾產品。

  語法: `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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。

`LIMIT` 子句用於限制 `SELECT`陳述式傳回的資料列數。一般而言，此子句會與 搭配使用`ORDER BY`，以確保結果具有決定性。

**語法** 

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

**參數**
+ **ALL**

  如果指定，查詢會傳回所有資料列。換句話說，如果指定此選項，則不會套用任何限制。
+ **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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 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_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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。

`EXPLAIN` 陳述式用於為輸入陳述式提供邏輯/物理計畫。根據預設，此子句僅提供實體計劃的相關資訊。

**語法** 

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

**參數**
+ **延伸** 

  產生剖析的邏輯計畫、分析的邏輯計畫、最佳化的邏輯計畫和實體計畫。

  剖析邏輯計畫是從查詢擷取的未解析計畫。

  分析的邏輯計畫會轉換，將 `unresolvedAttribute`和 轉換為`unresolvedRelation`完全輸入的物件。

  最佳化的邏輯計畫會透過一組最佳化規則進行轉換，進而產生實體計畫。
+ **CODEGEN** 

  如果有 和實體計畫，則產生陳述式的程式碼。
+ **COST** 

  如果計劃節點統計資料可用， 會產生邏輯計劃和統計資料。
+ **格式** 

  產生兩個區段：實體計畫大綱和節點詳細資訊。
+ **陳述式** 

  指定要解釋的 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。

`LIKE` 述詞用於搜尋特定模式。此述詞也支援具有量化器的多個模式`SOME`，包括 `ANY`、 和 `ALL`。

**語法** 

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

**參數**
+ **search\$1pattern **

  指定 LIKE 子句要搜尋的字串模式。它可以包含特殊模式比對字元：
  + `%` 符合零個或多個字元。
  + `_` 只比對一個字元。
+ **esc\$1char **

  指定逸出字元。預設逸出字元為 `\`。
+ **regex\$1pattern **

  指定要由 `RLIKE`或 `REGEXP`子句搜尋的規則運算式搜尋模式。
+ **量化器** 

  指定述詞量化器包括 `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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 OpenSearch SQL 命令和函數](#supported-directquery-sql)。

集合運算子用於將兩個輸入關係合併為單一輸入關係。OpenSearch SQL 支援三種類型的設定運算子：
+ `EXCEPT` 或 `MINUS`
+ `INTERSECT` 
+ `UNION` 

輸入關係必須具有相同數量的資料欄，以及個別資料欄的相容資料類型。

**EXCEPT** 

`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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 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`未指定 ，則如果排序順序為 ，則 NULLs會先排序，如果排序順序為 ，則 `ASC` NULLS 排序會最後排序`DESC`。

  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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 SQL 命令，請參閱 [支援的 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>

下表顯示 OpenSearch Dashboards 支援哪些 PPL 命令來查詢 CloudWatch Logs、Amazon S3 或 Security Lake，以及 CloudWatch Logs Insights 支援哪些命令。在查詢 CloudWatch Logs 時，CloudWatch Logs Insights 使用與 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 命令 | Description | CloudWatch Logs | Amazon S3 | Security Lake | 範例 命令 | 
| --- | --- | --- | --- | --- | --- | 
| [field 命令](#supported-ppl-fields-command) | 顯示一組需要投影的欄位。 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 |  <pre> fields field1, field2</pre>  | 
| [其中 命令](#supported-ppl-where-command) |  根據您指定的條件篩選資料。  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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>  | 
| [剖析命令](#supported-ppl-parse-command) |  從字串擷取規則表達式 (regex) 模式，並顯示擷取的模式。擷取的模式可以進一步用來建立新的欄位或篩選資料。  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 |  <pre>parse `field1` ".*/(?<field2>[^/]+$)"<br />| where field2 = "requestId"<br />| fields field2, `field2`<br />| head 1000</pre>  | 
| [模式命令](#supported-ppl-patterns-command) |  從文字欄位擷取日誌模式，並將結果附加到搜尋結果。依模式分組日誌可讓您更輕鬆地從大量日誌資料彙總統計資料，以進行分析和故障診斷。  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.svg) 不支援 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 |  <pre>eval field2 = `field1` * 2<br />| fields field1, field2<br />| head 20</pre>  | 
| [重新命名命令](#supported-ppl-rename-command) |  重新命名搜尋結果中的一個或多個欄位。  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 |  <pre>source=customer<br />| join ON c_custkey = o_custkey orders<br />| head 10</pre>  | 
| [查詢命令](#supported-ppl-lookup-commands) |  新增或取代查詢索引 （維度表） 中的資料，以豐富您的搜尋資料。您可以使用維度資料表中的值來擴展索引的欄位，並在符合查詢條件時附加或取代值  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.svg) 不支援 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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>  | 
| [子查詢命令](#supported-ppl-subquery-commands) | 在 Piped Processing Language (PPL) 陳述式中執行複雜的巢狀查詢。 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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>  | 
| [罕見命令](#supported-ppl-rare-command) |  尋找欄位清單中所有欄位頻率最低的值。  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 |  <pre> rare Field1 by Field2</pre>  | 
| [趨勢線命令](#supported-ppl-trendline-commands) | 計算欄位的移動平均值。 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援 ( 除外`count()`)  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 |  <pre> eventstats sum(field1) by field2</pre>  | 
| [平面命令](#supported-ppl-flatten-command) |  扁平化欄位， 欄位必須為此類型： `struct<?,?> or array<struct<?,?>>`  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 |  <pre> source=table | flatten field1</pre>  | 
| [欄位摘要](#supported-ppl-field-summary-command) | 計算每個欄位的基本統計資料 （計數、相異計數、最小值、最大值、平均值、標準差和平均值）。 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援 （每個查詢一個欄位） | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.svg) 不支援 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 |  <pre> describe schema.table</pre>  | 

## 函數
<a name="supported-ppl-functions"></a>


| PPL 函數 | Description | 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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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`)  |  對多個資料列執行計算以產生單一摘要值的內建函數。例如，**總**和、**計數**、**平均值**、**最大值**和**最小值**。  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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** （絕對值）、**圓 **（圓數）、**sqrt** （平方根）、**pow** （功率計算） 和 **ceil** （四捨五入至最接近的整數）。  | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/negative_icon.svg) 不支援 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/opensearch-service/latest/developerguide/images/success_icon.svg) 支援的 | ![\[alt text not found\]](http://docs.aws.amazon.com/zh_tw/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)。 Amazon CloudWatch 限制包括您可以查詢的 CloudWatch Log 群組數量、您可以執行的並行查詢數量上限、查詢執行時間上限，以及結果中傳回的資料列數量上限。無論您使用哪種語言查詢 CloudWatch Logs （即 OpenSearch PPL、SQL 和 Logs Insights QL)，限制都相同。

### PPL 命令
<a name="supported-ppl-commands-details"></a>

**Topics**
+ [comment](#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)
+ [field 命令](#supported-ppl-fields-command)
+ [平面命令](#supported-ppl-flatten-command)
+ [grok 命令](#supported-ppl-grok-command)
+ [head 命令](#supported-ppl-head-command)
+ [join 命令](#supported-ppl-join-commands)
+ [查詢命令](#supported-ppl-lookup-commands)
+ [剖析命令](#supported-ppl-parse-command)
+ [模式命令](#supported-ppl-patterns-command)
+ [罕見命令](#supported-ppl-rare-command)
+ [重新命名命令](#supported-ppl-rename-command)
+ [搜尋命令](#supported-ppl-search-command)
+ [sort 命令](#supported-ppl-sort-command)
+ [stats 命令](#supported-ppl-stats-command)
+ [子查詢命令](#supported-ppl-subquery-commands)
+ [top 命令](#supported-ppl-top-command)
+ [趨勢線命令](#supported-ppl-trendline-commands)
+ [其中 命令](#supported-ppl-where-command)
+ [欄位摘要](#supported-ppl-field-summary-command)
+ [expand 命令](#supported-ppl-expand-command)
+ [PPL 函數](#supported-ppl-functions-details)

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

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

您可以根據常見的維度和時間範圍來關聯不同的資料來源。

當您處理來自共用相同時段但未正式同步之各種垂直的大量資料時，這種相互關聯至關重要。

透過根據時間範圍和類似維度來關聯這些不同的資料來源，您可以充實資料並發現寶貴的洞見。

**範例**  
可觀測性網域有三種不同的資料來源：
+ 日誌
+ 指標
+ 追蹤

這些資料來源可能會共用共同維度。若要從一個資料來源轉換到另一個資料來源，您需要正確建立關聯。使用語意命名慣例，您可以識別跨日誌、追蹤和指標的共用元素。

範例：

```
{
  "@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": 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": {
         ...
        }
      }
    }
  }
}
```

在此方法中，您可以看到`ip`與 elb 日誌建立關聯的 `traceId`和 http 的用戶端/伺服器，以進一步了解系統的行為和條件。

**新的相互關聯查詢命令**  
以下是允許此類調查的新命令：

```
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    
```

對於參與相互關聯聯結的每個欄位，您應該提供相關的映射陳述式，其中包含此相互關聯命令要聯結的所有資料表。

**範例**  
在此範例中，有 2 個來源： `alb_logs, traces`

有 2 個欄位： `traceId, ip`

有兩個映射陳述式： `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]
```

觸媒引擎會根據最有效率的聯結順序來最佳化此查詢。

#### dedup 命令
<a name="supported-ppl-dedup-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `dedup`命令，根據指定的欄位從搜尋結果中移除相同的文件。

**語法**  
使用下列語法：

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

**`int`**
+ 選用。
+ 當您指定 <int> 時，`dedup`命令會保留每個組合的多個事件。<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：連續文件中的 Dedup**  
此範例示範如何在連續文件中進行資料刪除。

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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#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`

**評估與案例範例：**  


```
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')
```

**使用另一個案例評估範例：**  


假設：`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`

**評估與案例範例：**  


```
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')
```

**使用另一個案例評估範例：**  


```
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
```

**限制**
+ 不支援覆寫現有欄位。嘗試這樣做的查詢會擲回例外狀況，並顯示「參考「a」不明確」訊息。

  ```
  - `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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `eventstats`命令，透過計算的摘要統計資料來豐富您的事件資料。它的運作方式是分析事件中的指定欄位、計算各種統計指標，然後將這些結果做為新欄位附加到每個原始事件。

**eventstats 的關鍵層面**

1. 它會在整個結果集或在定義的群組中執行計算。

1. 原始事件保持不變，新增新欄位以包含統計結果。

1. 命令對於比較分析、識別極端值或為個別事件提供額外的內容特別有用。

**統計資料和 eventstats 之間的差異**  
`stats` 和 `eventstats`命令都用於計算統計資料，但它們的運作方式和產生的內容有一些關鍵差異。

**輸出格式**
+ `stats`：產生只有計算統計資料的摘要資料表。
+ `eventstats`：將計算的統計資料新增為現有事件的新欄位，保留原始資料。

**事件保留**
+ `stats`：將結果設定為僅統計摘要，捨棄個別事件。
+ `eventstats`：保留所有原始事件，並新增具有計算統計資料的新欄位。

**使用案例**
+ `stats`：最適合建立摘要報告或儀表板。通常用作總結結果的最終命令。
+ `eventstats`：當您需要以統計內容豐富事件以進行進一步分析或篩選時很有用。可用於搜尋中，以新增可用於後續命令的統計資料。

**語法**  
使用下列語法：

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

**聚合**
+ 強制性。
+ 彙總函數。
+ 彙總的引數必須是 欄位。

**依 -clause**
+ 選用。
+ 語法: `by [span-expression,] [field,]...`
+ 依子句可包含純量函數和彙總函數等欄位和表達式。您也可以使用跨度子句，將特定欄位分割為相等間隔的儲存貯體。eventstats 命令接著會根據這些跨度儲存貯體執行彙總。
+ 預設：如果您未依子句指定 ，則 eventstats 命令會彙總整個結果集。

**span-expression**
+ 選用，最多一個。
+ 語法: `span(field_expr, interval_expr)`
+ 間隔表達式的單位預設為自然單位。不過，對於日期和時間類型欄位，您需要在使用日期/時間單位時，在間隔表達式中指定單位。

  例如，若要將欄位分割`age`為儲存貯體 10 年，請使用 `span(age, 10)`。對於以時間為基礎的欄位，您可以使用 將`timestamp`欄位分割為每小時間隔`span(timestamp, 1h)`。


**可用的時間單位**  

| 跨度間隔單位 | 
| --- | 
| 毫秒 (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   |
+----------------+----------+-----------+----------+-----+--------+-----------------------+-------------+---------------------------+--------+-------+-----+
```

**Usage**
+ `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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `expand`命令來扁平化 類型的欄位：
+ `Array<Any>`
+ `Map<Any>`

**語法**  
使用下列語法：

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

**field**
+ 要擴展 （分解） 的欄位。必須為支援的類型。

**別名**
+ 選用。要使用的名稱，而非原始欄位名稱。

**Usage**  
`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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

`explain` 命令可協助您了解查詢執行計劃，讓您能夠分析和最佳化查詢，以獲得更好的效能。此簡介提供 explain 命令的用途及其在查詢最佳化中重要性的簡要概觀。

**Comment**
+ `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`

**評估**  
假設：`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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

**Description**  
使用 `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 取代中指定的值。

**範例 1：填入一個欄位**  
此範例示範如何在單一欄位上使用 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：將 fillnull 套用至具有各種 null 取代值的多個欄位。**  
此範例顯示 fillnull，其中包含用於取代 null 的各種值。
+ `/error` 在 `request_path` 欄位中
+ `1970-01-01 00:00:00` 在 `timestamp` 欄位中

```
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    |
```

#### field 命令
<a name="supported-ppl-fields-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `fields`命令來保留或移除搜尋結果中的欄位。

**語法**  
使用下列語法：

```
field [+|-] <field-list> 
```
+ `index`：選用。

  如果使用加號 (＋)，則只會保留欄位清單中指定的欄位。

  如果使用減號 (-)，則會移除欄位清單中指定的所有欄位。

  *預設*：\$1
+ `field list`：強制性。要保留或移除的欄位逗號分隔清單。

**範例 1：從結果中選取指定的欄位**  
此範例說明如何從搜尋結果中擷取 `firstname`、 `account_number`和 `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`
```

#### 平面命令
<a name="supported-ppl-flatten-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用平面命令來展開下列類型的欄位：
+ `struct<?,?>`
+ `array<struct<?,?>>`

**語法**  
使用下列語法：

```
flatten <field>
```
+ *欄位*：要扁平化的欄位。欄位必須為支援的類型。

**結構描述**


| col\$1name | data\$1type | 
| --- | --- | 
| \$1time | string | 
| 橋接器 | array<struct<length：bigint，name：string>> | 
| 城市 | string | 
| coor | struct<alt：bigint，lat：double，long：double> | 
| 國家/地區 | string | 

**資料**  



| \$1time | 橋接器 | 城市 | coor | 國家/地區 | 
| --- | --- | --- | --- | --- | 
| 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】 | 維尼斯 | \$12， 45.4408， 12.3155\$1 | 義大利 | 
| 2024-09-13T12：00：00 | 【\$1\$1\$1\$1、Charles Bridge\$1、\$1343、Legion Bridge\$1】 | 布拉格 | \$1200、50.0755、14.4378\$1 | 捷克 | 
| 2024-09-13T12：00：00 | 【\$1375， Chain Bridge\$1， \$1333， Liberty Bridge\$1】 | 布達佩斯 | \$196、47.4979、19.0402\$1 | 匈牙利 | 
| 1990-09-13T12：00：00 | NULL | 華沙 | NULL | 波蘭 | 

**範例 1：平面化結構**  
此範例示範如何扁平化結構欄位。

PPL 查詢：

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


| \$1time | 橋接器 | 城市 | 國家/地區 | 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】 | 維尼斯 | 義大利 | 2 | 45.4408 | 12.3155 | 
| 2024-09-13T12：00：00 | 【\$1516， Charles Bridge\$1， \$1343， Legion Bridge\$1】 | 布拉格 | 捷克 | 200 | 50.0755 | 14.4378 | 
| 2024-09-13T12：00：00 | 【\$1375， Chain Bridge\$1， \$1333， Liberty Bridge\$1】 | 布達佩斯 | 匈牙利 | 96 | 47.4979 | 19.0402 | 
| 1990-09-13T12：00：00 | NULL | 華沙 | 波蘭 | NULL | NULL | NULL | 

**範例 2：平面陣列**  
此範例示範如何扁平化結構欄位的陣列。

PPL 查詢：

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


| \$1time | 城市 | coor | 國家/地區 | length | name | 
| --- | --- | --- | --- | --- | --- | 
| 2024-09-13T12：00：00 | 倫敦 | \$135、51.5074、-0.1278\$1 | 英國 | 801 | 塔橋 | 
| 2024-09-13T12：00：00 | 倫敦 | \$135、51.5074、-0.1278\$1 | 英國 | 928 | 倫敦大橋 | 
| 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 | 維尼斯 | \$12， 45.4408， 12.3155\$1 | 義大利 | 48 | Rialto 橋接器 | 
| 2024-09-13T12：00：00 | 維尼斯 | \$12， 45.4408， 12.3155\$1 | 義大利 | 11 | 嘆號的橋接 | 
| 2024-09-13T12：00：00 | 布拉格 | \$1200、50.0755、14.4378\$1 | 捷克 | 516 | 查爾斯大橋 | 
| 2024-09-13T12：00：00 | 布拉格 | \$1200、50.0755、14.4378\$1 | 捷克 | 343 | Legion 橋接器 | 
| 2024-09-13T12：00：00 | 布達佩斯 | \$196、47.4979、19.0402\$1 | 匈牙利 | 375 | Chain Bridge | 
| 2024-09-13T12：00：00 | 布達佩斯 | \$196、47.4979、19.0402\$1 | 匈牙利 | 333 | 自由大橋 | 
| 1990-09-13T12：00：00 | 華沙 | NULL | 波蘭 | NULL | NULL | 

**範例 3：平面化陣列和結構**  
此範例示範如何扁平化多個欄位。

PPL 查詢：

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


| \$1time | 城市 | 國家/地區 | length | name | alt | lat | long | 
| --- | --- | --- | --- | --- | --- | --- | --- | 
| 2024-09-13T12：00：00 | 倫敦 | 英國 | 801 | 塔橋 | 35 | 51.5074 | -0.1278 | 
| 2024-09-13T12：00：00 | 倫敦 | 英國 | 928 | 倫敦大橋 | 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 | 維尼斯 | 義大利 | 48 | Rialto 橋接器 | 2 | 45.4408 | 12.3155 | 
| 2024-09-13T12：00：00 | 維尼斯 | 義大利 | 11 | 嘆號的橋接 | 2 | 45.4408 | 12.3155 | 
| 2024-09-13T12：00：00 | 布拉格 | 捷克 | 516 | 查爾斯大橋 | 200 | 50.0755 | 14.4378 | 
| 2024-09-13T12：00：00 | 布拉格 | 捷克 | 343 | Legion 橋接器 | 200 | 50.0755 | 14.4378 | 
| 2024-09-13T12：00：00 | 布達佩斯 | 匈牙利 | 375 | Chain Bridge | 96 | 47.4979 | 19.0402 | 
| 2024-09-13T12：00：00 | 布達佩斯 | 匈牙利 | 333 | 自由橋 | 96 | 47.4979 | 19.0402 | 
| 1990-09-13T12：00：00 | 華沙 | 波蘭 | NULL | NULL | NULL | NULL | NULL | 

#### grok 命令
<a name="supported-ppl-grok-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

`grok` 命令會剖析具有 grok 模式的文字欄位，並將結果附加至搜尋結果。

**語法**  
使用下列語法：

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

**field**
+ 強制性。
+ 欄位必須是文字欄位。

**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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

聯結命令可讓您根據常見欄位結合來自多個來源的資料，讓您執行複雜的分析，並從分散式資料集取得更深入的洞見

**結構描述**  
至少有兩個索引，`otel-v1-apm-span-*`（大型） 和 `otel-v1-apm-service-map`（小型）。

索引的相關欄位：

**`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
```

#### 查詢命令
<a name="supported-ppl-lookup-commands"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `lookup`命令新增或取代查詢索引 （維度表） 中的資料，以豐富您的搜尋資料。此命令可讓您使用維度資料表中的值來延伸索引的欄位。您也可以使用它在符合查詢條件時附加或取代值。`lookup` 命令比 `Join`命令更適合使用靜態資料集來充實來源資料。

**語法**  
使用下列語法：

```
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 的相符值取代或附加。如果您指定新的欄位名稱，則會將其新增至結果。

**取代 \$1 附加**
+ 選用。
+ 預設：REPLACE
+ 指定如何處理相符的值。如果您指定 REPLACE，則 <lookupIndex> 欄位中相符的值會覆寫結果中的值。如果您指定 `APPEND`，則 <lookupIndex> 欄位中相符的值只會附加到結果中缺少的值。

**Usage**
+ lookUP <lookupIndex> ID AS cid REPLACE 郵件 AS 電子郵件
+ lookUP <lookupIndex> 名稱 REPLACE 郵件 AS 電子郵件
+ lookUP <lookupIndex> id AS cid、name APPEND 地址、郵件 AS 電子郵件
+ 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
```

#### 剖析命令
<a name="supported-ppl-parse-command"></a>

`parse` 命令會剖析具有規則表達式的文字欄位，並將結果附加到搜尋結果。

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

**語法**  
使用下列語法：

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

**`field`**
+ 強制性。
+ 欄位必須是文字欄位。

**`pattern`**
+ 必要字串。
+ 這是規則表達式模式，用於從指定文字欄位擷取新欄位。
+ 如果新的欄位名稱已存在，則會取代原始欄位。

**Regular expression (常規表達式)**  
規則表達式模式用於比對每個文件的整個文字欄位與 Java regex 引擎。表達式中的每個具名擷取群組都會成為新的`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   |
+----------------+----------------+
```

**限制**  
剖析命令有一些限制：
+ 剖析定義的欄位無法再次剖析。

  下列命令無法運作：

  ```
  source=accounts | parse address '\d+ (?<street>.+)' | parse street '\w+ (?<road>\w+)'
  ```
+ 剖析定義的欄位無法以其他命令覆寫。

  `where` 不符合任何文件，因為 `street`無法覆寫：

  ```
  source=accounts | parse address '\d+ (?<street>.+)' | eval street='1' | where street='1' ;        
  ```
+ 剖析所使用的文字欄位無法覆寫。

  `street` 無法成功剖析 ，因為 `address` 被覆寫：

  ```
  source=accounts | parse address '\d+ (?<street>.+)' | eval address='1' ;        
  ```
+ 在 `stats`命令中使用剖析定義的欄位後，就無法進行篩選或排序。

  `where` 下列命令中的 無法運作：

  ```
  source=accounts | parse email '.+@(?<host>.+)' | stats avg(age) by host | where host=pyrami.com ;        
  ```

#### 模式命令
<a name="supported-ppl-patterns-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

`patterns` 命令會從文字欄位擷取日誌模式，並將結果附加至搜尋結果。依模式分組日誌可讓您更輕鬆地從大量日誌資料彙總統計資料，以進行分析和故障診斷。

**語法**  
使用下列語法：

```
patterns [new_field=<new-field-name>] [pattern=<pattern>] <field>    
```

**new-field-name**
+ 選用字串。
+ 這是擷取模式的新欄位名稱。
+ 預設值為 `patterns_field`。
+ 如果名稱已存在，則會取代原始欄位。

**pattern**
+ 選用字串。
+ 這是應該從文字欄位篩選出的字元規則運算式模式。
+ 如果不存在，預設模式為英數字元 (`[a-zA-Z\d]`)。

**field**
+ 強制性。
+ 欄位必須是文字欄位。

**範例 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：使用自訂 regex 模式擷取日誌模式**  
此範例示範如何使用使用者定義的模式，從原始日誌欄位擷取標點符號。

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/."                                            |
+-----------------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------+
```

**限制**  
模式命令具有與剖析命令相同的限制。

#### 罕見命令
<a name="supported-ppl-rare-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `rare`命令來尋找欄位清單中所有欄位最不常見的值元組。

**注意**  
群組區分欄位的每個不同值元組最多傳回 10 個結果。

**語法**  
使用下列語法：

```
rare [N] <field-list> [by-clause] rare_approx [N] <field-list> [by-clause]
```

**field-list**
+ 強制性。
+ 欄位名稱的逗號分隔清單。

**依 -clause**
+ 選用。
+ 要分組結果的一個或多個欄位。

**N**
+ 要傳回的結果數目。
+ 預設：10

**罕見\$1大約**
+ [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    |
+----------+-------+
```

#### 重新命名命令
<a name="supported-ppl-rename-command"></a>

使用 `rename`命令來變更搜尋結果中一或多個欄位的名稱。

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

**語法**  
使用下列語法：

```
rename <source-field> AS <target-field>["," <source-field> AS <target-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        
  ```

#### 搜尋命令
<a name="supported-ppl-search-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `search`命令從 索引擷取文件。`search` 命令只能用作 PPL 查詢中的第一個命令。

**語法**  
使用下列語法：

```
search source=[<remote-cluster>:]<index> [boolean-expression]    
```

**search**
+ 選用。
+ 可省略的搜尋關鍵字。

**index**
+ 強制性。
+ 搜尋命令必須指定要查詢的索引。
+ 對於跨叢集搜尋`<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`命令，依指定的欄位排序搜尋結果。

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

**語法**  
使用下列語法：

```
sort <[+|-] sort-field>...
```

**[\$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`命令從搜尋結果計算彙總。

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

**NULL/MISSING 值處理**  



**NULL/MISSING 值處理**  

| 函式 | NULL | 缺少 | 
| --- | --- | --- | 
| COUNT | 未計數 | 未計數 | 
| SUM | Ignore | Ignore | 
| AVG | Ignore | Ignore | 
| MAX | Ignore | Ignore | 
| MIN | Ignore | Ignore | 

**語法**  
使用下列語法：

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

**聚合**
+ 強制性。
+ 套用至欄位的彙總函數。

**依 -clause**
+ 選用。
+ 語法: `by [span-expression,] [field,]...`
+ 指定用於分組彙總結果的欄位和表達式。依項目可讓您使用欄位和表達式將彙總結果分組。您可以使用純量函數、彙總函數，甚至是跨度表達式，將特定欄位分割成相等間隔的儲存貯體。
+ 預設：如果未指定 `<by-clause>` ，則 stats 命令會傳回代表整個結果集彙總的單一資料列。

**span-expression**  

+ 選用，最多一個。
+ 語法: `span(field_expr, interval_expr)`
+ 間隔表達式的單位預設為自然單位。如果 欄位是日期和時間類型欄位，且間隔是以日期/時間單位為單位，您可以在間隔表達式中指定單位。
+ 例如，將`age`欄位分割為儲存貯體 10 年，看起來像 `span(age, 10)`。若要將時間戳記欄位分割為每小時間隔，請使用 `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(field [, size])`傳回欄位的原始值。它不保證值的順序。

**field**
+ 強制性。
+ 欄位必須是文字欄位。

**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：計算欄位的不同計數**  
若要取得欄位不同值的計數，您可以使用 `DISTINCT_COUNT`（或 `DC`) 函數而非 `COUNT`。此範例會計算所有帳戶的性別欄位計數和相異計數。

```
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`
```

#### 子查詢命令
<a name="supported-ppl-subquery-commands"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `subquery`命令在 Piped Processing Language (PPL) 陳述式中執行複雜的巢狀查詢。

```
source=logs | where field in [ subquery source=events | where condition | fields field ]
```

在此範例中，主要搜尋 (`source=logs`) 會依子查詢 () 的結果進行篩選`source=events`。

子查詢命令支援多層巢狀化，以進行複雜的資料分析。

**巢狀子查詢範例**  


```
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 ]` （使用子查詢進行搜尋篩選）
+ `source = outer a not in [ source = inner | fields b ]` （使用子查詢進行搜尋篩選）
+ `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 ]` （使用子查詢進行搜尋篩選）
+ `source = outer not exists [ source = inner | where a = c ]` （使用子查詢進行搜尋篩選）
+ `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 ]` （不存在不相關）
+ `source = outer | where not exists [ source = inner | where c > 10 ]` （不存在不相關）
+ `source = outer | where exists [ source = inner ] | eval l = "nonEmpty" | fields l` （存在特殊不相關）

**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`

在 中：
+ `source = outer | where a > [ source = inner | stats min(c) ] | fields a`

在搜尋篩選條件中：
+ `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`

在 中：
+ `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`

在搜尋篩選條件中：
+ `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`不是子查詢表達式，而是在聯結或來源子句中常用的子查詢計畫。
+ `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 <boolean expression> | ...    
```

搜尋篩選條件：

```
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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `top`命令來尋找欄位清單中所有欄位的最常見值元組。

**語法**  
使用下列語法：

```
top [N] <field-list> [by-clause] top_approx [N] <field-list> [by-clause]
```

**N**
+ 要傳回的結果數目。
+ 預設：10

**field-list**
+ 強制性。
+ 欄位名稱的逗號分隔清單。

**依 -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    |
+----------+-------+
```

#### 趨勢線命令
<a name="supported-ppl-trendline-commands"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `trendline`命令來計算欄位的移動平均值。

**語法**  
使用下列語法

```
TRENDLINE [sort <[+|-] sort-field>] SMA(number-of-datapoints, field) [AS alias] [SMA(number-of-datapoints, field) [AS alias]]... 
```

**[\$1\$1-]**
+ 選用。
+ 加號 【＋】 表示先有 NULL/MISSING 值的遞增順序。
+ 減號 【-】 代表 NULL/MISSING 值最後的遞減順序。
+ 預設：先以 NULL/MISSING 值遞增順序。

**sort-field**
+ 使用排序時為強制性。
+ 用於排序的欄位。

**number-of-datapoints**
+ 強制性。
+ 計算移動平均值的資料點數目。
+ 必須大於零。

**field**
+ 強制性。
+ 應計算移動平均值的欄位名稱。

**別名**
+ 選用。
+ 包含移動平均值的產生資料欄名稱。

僅支援簡易移動平均 (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 遞減排序的兩個和三個資料點，計算溫度的兩個簡單移動平均值。

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|
+-----------+---------+--------------------+------------+------------------+
```

#### 其中 命令
<a name="supported-ppl-where-command"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

`where` 命令使用 bool-expression 來篩選搜尋結果。它只會在 bool-expression 評估為 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 命令，請參閱 [命令](#supported-ppl-commands)。

使用 `fieldsummary`命令來計算每個欄位的基本統計資料 （計數、相異計數、最小值、最大值、平均值、平均值），並判斷每個欄位的資料類型。此命令可與上述任何管道搭配使用，並將它們納入考量。

**語法**  
請使用下列語法。對於 CloudWatch Logs 使用案例，查詢中僅支援一個欄位。

```
... | fieldsummary <field-list> (nulls=true/false)
```

**包含欄位**
+ 將統計資料收集到統一結果集的所有資料欄清單。

**Null**
+ 選用。
+  如果設為 true，請在彙總計算中包含 null 值 （數值以 null 取代為零）。

**範例 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

使用 `expand`命令來扁平化 Array<Any> 或 Map<Any> 類型的欄位，為每個元素或鍵值對產生個別資料列。

**語法**  
使用下列語法：

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

**field**
+ 要擴展 （分解） 的欄位。
+ 欄位必須為支援的類型。

**別名**
+ 選用。
+ 要使用的名稱，而非原始欄位名稱。

**使用指引**  
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 等。使用多個展開命令會為每個複合陣列或映射內的所有內部元素建立笛卡兒產品。

**有效的 SQL 下推查詢**  
expand 命令會使用 LATERAL VIEW explode 轉換為同等的 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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

##### ISNULL
<a name="supported-ppl-condition-functions-isnull"></a>

**描述**：如果 欄位為 null，則`isnull(field)`傳回 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>

**描述**：如果欄位不是 null，則`isnotnull(field)`傳回 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>

**描述**：`field2`如果 `field1`為 null，則`ifnull(field1, 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>

**描述**：`expr1`如果條件為 true，則`if(condition, expr1, expr2)`傳回 ，否則傳回 `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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

##### MD5
<a name="supported-ppl-cryptographic-functions-md5"></a>

MD5 會計算 MD5 摘要，並以 32 個字元的十六進位字串傳回值。

**用量**： `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 的十六進位字串結果。

**用量**： `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) 的十六進位字串結果。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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

##### `DAY`
<a name="supported-ppl-date-time-functions-day"></a>

**用量**： `DAY(date)`擷取日期的月份日期，範圍介於 1 到 31。

**引數類型**：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 到 31。

**引數類型**：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 到 31。

**引數類型**：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 到 366。

**引數類型**：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 到 366。

**引數類型**：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 到 3001-01-18 23：59：59.999999 (0 到 32536771199.999999 epoch 時間） 的範圍內，函數會傳回 `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

**範例**：

```
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 到 59 範圍內的整數表示。

**引數類型**：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 到 59 範圍內的整數表示。

**引數類型**：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 到 12 （其中 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 到 12 （其中 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 到 12 （其中 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>

**用量**：以 'YYYY-MM-DD hh：mm：ss' 格式`TIMESTAMP`的值`NOW`傳回目前的日期和時間。此值以叢集時區表示。

**注意**  
`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 到 4。

**引數類型**：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 到 59。

**引數類型**：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 到 59。

**引數類型**：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

**Antonyms**： `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>

**用量**：以 'YYYY-MM-DD hh：mm：ss.nnnnnn' 格式`TIMESTAMP`的值`SYSDATE()`傳回目前的日期和時間。

`SYSDATE()`會傳回其執行的確切時間。這與 NOW() 不同，它會傳回常數時間，指出陳述式何時開始執行。

**選用引數類型**：INTEGER (0 到 6) - 指定傳回值中小數秒的位數。

**傳回類型**：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` 是字串，則會解譯為時間戳記。對於非字串引數，函數`expr`會使用 UTC 時區轉換為時間戳記。當 `expr` 是`TIME`值時，函數會在轉換之前套用今天的日期。

與兩個引數搭配使用時， 會將時間表達式 (`expr2`) `TIMESTAMP(expr1, expr2)`新增至日期或時間戳記表達式 (`expr1`)，並將結果傳回為時間戳記值。

**引數類型**：STRING/DATE/TIME/TIMESTAMP

**傳回類型映射**：

(STRING/DATE/TIME/時間戳記） -> 時間戳記

(STRING/DATE/TIME/TIMESTAMP、STRING/DATE/TIME/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 年初開始的 Epoch 起的秒數）。如果未提供引數，則會傳回目前的 Unix 時間。

日期引數可以是 `DATE`、`TIMESTAMP`字串或下列其中一種格式的數字：`YYMMDD`、`YYYYMMDD`、 `YYMMDDhhmmss`或 `YYYYMMDDhhmmss`。如果引數包含時間元件，則可能選擇性地包含小數秒。

如果引數的格式無效，或超出 1970-01-01 00：00：00 到 3001-01-18 23：59：59.999999 的範圍 (epoch 時間為 0 到 32536771199.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 到 9999 之間，或傳回 "zero" 日期的年份。

**引數類型**：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

**Antonyms**： `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

**Antonyms**： `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 （秒、分鐘、小時、日、週、月、季、年） 
+ 整數：INTEGER 
+ 日期：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 （秒、分鐘、小時、日、週、月、季、年） 
+ start：DATE、TIMESTAMP 或 STRING 
+ 結束：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>

**用量**： 以 'YYYY-MM-DD hh：mm：ss' 的值`UTC_TIMESTAMP`傳回目前的 UTC 時間戳記。

**傳回類型**：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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

運算式，特別是值運算式，會傳回純量值。表達式有不同的類型和形式。例如，有以原子表達式和算術、述詞和函數表達式為基礎的常值。您可以在不同的子句中使用表達式，例如在 `Filter`和 `Stats`命令中使用算術表達式。

**運算子**

算術表達式是由數值常值和二進位算術運算子形成的表達式，如下所示：

1. `+`：新增。

1. `-`：減去。

1. `*`：乘以。

1. `/`：除數 （對於整數，結果是捨棄分數部分的整數）

1. `%`：Modulo （僅與整數搭配使用；結果是分割的其餘部分）

**優先順序**

使用括號來控制算術運算子的優先順序。否則，會先執行優先順序較高的運算子。

**類型轉換**

查詢運算子簽章時，會執行隱含類型轉換。例如，實數`+`的整數會比對`+(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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#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` 都必須有效且非空白/非空。

##### PPL JSON 函數
<a name="supported-ppl-json-functions"></a>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#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> 必須是 STRING。
+ <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 路徑，從 JSON 字串`json_extract(jsonStr, path)`擷取 JSON 物件。如果輸入 JSON 字串無效，函數會傳回 null。

**引數類型**：STRING、STRING

**傳回類型**：STRING
+ 有效 JSON 物件格式的 STRING 表達式。
+ `NULL` 會在 JSON 無效時傳回。

**範例**：

```
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】。函數`NULL`會傳回任何其他有效的 JSON 字串、空字串或無效的 JSON。

**範例**：

```
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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#supported-ppl-functions)。

##### `EXISTS`
<a name="supported-ppl-lambda-functions-exists"></a>

**用量**：`exists(array, lambda)`評估 Lambda 述詞是否保留陣列中的一或多個元素。

**引數類型**：ARRAY、LAMBDA

**傳回類型**：BOOLEAN。`TRUE` 如果陣列中至少有一個元素符合 Lambda 述詞，則傳回 ，否則傳回 `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>

**用量**：使用指定的 Lambda 函數`filter(array, 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>

**用量**： 使用 Lambda `transform(array, 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>

**用量**：套用 lambda 函數，將陣列`reduce(array, start, merge_lambda, finish_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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#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 的電弧餘弦。`NULL` 如果 x 不在 -1 到 1 的範圍內，則傳回 。

**引數類型**：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 的電弧正弦。`NULL` 如果 x 不在 -1 到 1 的範圍內，則傳回 。

**引數類型**：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 -> 雙

**範例**：

```
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>

**用量**： 將數字 x 從基礎`CONV(x, a, b)`轉換為 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 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>

**用量**： 將 x 從弧度`DEGREES(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()`傳回 Euler 的號碼。

**傳回類型**：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. log(B， x) 的基本 e 對數，相當於 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 是非零值，則 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>

**用量**： 將 x 從度數`RADIANS(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>

**用量**：將引數 x `ROUND(x, d)`四捨五入為小數位數。如果您未指定 d，則預設為 0。

**引數類型**：INTEGER/LONG/FLOAT/DOUBLE

**傳回類型映射**：
+ （整數/長 【，整數】) -> 長
+ （浮點數/雙 【，整數】) -> 長

**範例**：

```
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`傳回引數的符號為 -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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#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>

**注意**  
若要查看哪些 AWS 資料來源整合支援此 PPL 函數，請參閱 [函數](#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！=0 | N/A | N/A | N/A | 
| BOOLEAN | Note1 | v？1：0 |  | N/A | N/A | N/A | 
| TIMESTAMP | Note1 | N/A | N/A |  | DATE() | TIME() | 
| DATE | Note1 | N/A | N/A | N/A |  | N/A | 
| TIME | Note1 | N/A | N/A | N/A | N/A |  | 

**轉換為字串範例：**

```
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    |
+---------+
```