

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

# 使用日期和時間的查詢
<a name="query-examples-waf-logs-date-time"></a>

本節中的範例包括使用日期和時間值的查詢。
+ [Return the timestamp field in human-readable ISO 8601 format](#waf-example-return-human-readable-timestamp)
+ [Return records from the last 24 hours](#waf-example-return-records-last-24-hours)
+ [Return records for a specified date range and IP address](#waf-example-return-records-date-range-and-ip)
+ [For a specified date range, count the number of IP addresses in five minute intervals](#waf-example-count-ip-addresses-in-date-range)
+ [Count the number of X-Forwarded-For IP in the last 10 days](#waf-example-count-x-forwarded-for-ip)

**Example – 以人類看得懂的 ISO 8601 格式傳回時間戳記欄位**  
以下查詢會使用 `from_unixtime` 和 `to_iso8601` 函數，以人類看得懂的 ISO 8601 格式傳回 `timestamp` 欄位 (例如 `2019-12-13T23:40:12.000Z`，而非 `1576280412771`) 查詢也會傳回 HTTP 來源名稱、來源 ID 和請求。  

```
SELECT to_iso8601(from_unixtime(timestamp / 1000)) as time_ISO_8601,
       httpsourcename,
       httpsourceid,
       httprequest
FROM waf_logs
LIMIT 10;
```

**Example – 傳回過去 24 小時的記錄**  
以下查詢會使用 `WHERE` 子句中的篩選條件，傳回過去 24 小時記錄的 HTTP 來源名稱、HTTP 來源 ID 和 HTTP 請求欄位。  

```
SELECT to_iso8601(from_unixtime(timestamp/1000)) AS time_ISO_8601, 
       httpsourcename, 
       httpsourceid, 
       httprequest 
FROM waf_logs
WHERE from_unixtime(timestamp/1000) > now() - interval '1' day
LIMIT 10;
```

**Example – 傳回指定日期範圍和 IP 地址的記錄**  
以下查詢會列出指定用戶端 IP 地址的指定日期範圍內的記錄。  

```
SELECT * 
FROM waf_logs 
WHERE httprequest.clientip='53.21.198.66' AND "date" >= '2021/03/01' AND "date" < '2021/03/31'
```

**Example – 如果是指定的日期範圍，則會計算每隔五分鐘的 IP 地址數量**  
以下查詢會針對特定日期範圍，計算每隔五分鐘的 IP 地址數量。  

```
WITH test_dataset AS 
  (SELECT 
     format_datetime(from_unixtime((timestamp/1000) - ((minute(from_unixtime(timestamp / 1000))%5) * 60)),'yyyy-MM-dd HH:mm') AS five_minutes_ts,
     "httprequest"."clientip" 
     FROM waf_logs 
     WHERE "date" >= '2021/03/01' AND "date" < '2021/03/31')
SELECT five_minutes_ts,"clientip",count(*) ip_count 
FROM test_dataset 
GROUP BY five_minutes_ts,"clientip"
```

**Example – 計算過去 10 天內的 X-Forwarded-For IP 數量**  
以下查詢會篩選請求標頭，並計算過去 10 天內的 X-Forwarded-For IP 數量。  

```
WITH test_dataset AS
  (SELECT header
   FROM waf_logs
   CROSS JOIN UNNEST (httprequest.headers) AS t(header)
   WHERE from_unixtime("timestamp"/1000) > now() - interval '10' DAY) 
SELECT header.value AS ip,
       count(*) AS COUNT 
FROM test_dataset 
WHERE header.name='X-Forwarded-For' 
GROUP BY header.value 
ORDER BY COUNT DESC
```

如需有關日期和時間函數的詳細資訊，請參閱 Trino 文件中的 [Date and time functions and operators](https://trino.io/docs/current/functions/datetime.html) (日期和時間函數和運算子)。