dicemy/DataClawEval huggingface dataset:
# From input table internal_platform_db.t_eis_feedaggregator2_feedforredd (HiveSQL)

## Prompt
Task Objective: Extract qualifying records from the input table, parse the JSON array, and explode it into multiple rows, then output to the target table.

Input:
- `internal_platform_db.t_eis_feedaggregator2_feedforreddot_check_result_summary_classification_df_query_engine_152`

Processing Rules:
1. Filter condition: `ds='20260608'`, `regexp_replace(second_update_date, '-', '') = ds`, `second_status in (1, 2)`
2. Core transformation:
   - Extract `$.info.titles` from the `json_buffer_` field as a JSON array string
   - Remove the outermost square brackets of the array, replace `},{` with `}|{`, and split by `|` to obtain multiple JSON objects
   - Use `LATERAL VIEW explode` to expand into multiple rows, with one `title_obj` per row
   - Extract from each `title_obj`: `$.title`, `$.title_type`, `$.quality`
3. No joins, single-table processing

Output Requirements:
- Output field order: `ds`, `feedid`, `feedid_v1`, `type_source`, `classification`, `title`, `title_type`, `quality`, `second_status`
- The `ds` field value is fixed as `20260608`
- The `feedid_v1` field value equals `feedid`
- No deduplication or aggregation required

Write Requirements:
- Output table: `internal_platform_db.dws_rd_feedaggregator_feed_title_quality_di_cand_query_engine_152`
- Partition field: `ds=20260608`
- Write method: `INSERT OVERWRITE`

Please write the final HiveSQL to `result.sql` and execute it.

## Reference Solution
INSERT OVERWRITE TABLE internal_platform_db.dws_rd_feedaggregator_feed_title_quality_di_query_engine_152 PARTITION (ds = '20260608')
WITH tbl AS (
SELECT
feedid,
type_source,
classification,
second_status,
get_json_object(json_buffer_, '$.info.titles') AS titles_info
FROM internal_platform_db.t_eis_feedaggregator2_feedforreddot_check_result_summary_classification_df_query_engine_152
WHERE ds='20260608'
AND regexp_replace(second_update_date, '-', '') = ds
AND second_status in (1, 2)
)
SELECT
feedid,
feedid as feedid_v1,
type_source,
classification,
get_json_object(title_obj, '$.title') AS title,
get_json_object(title_obj, '$.title_type') AS title_type,
get_json_object(title_obj, '$.quality') AS quality,
second_status
FROM tbl
LATERAL VIEW explode(
split(
regexp_replace(
regexp_replace(
titles_info,
'^\\[|\\]$',
''
),
'\\}\\,\\{',
'}\\|\\{'
),
'\\|'
)
) exploded AS title_obj
# IM平台Q群离线报告子分区过滤 (PrestoSQL)

## Prompt
**任务目标**：从IM平台Q群离线报告原始日志中，筛选指定appid下包含"诈骗"标签的记录，提取关键字段写入输出表。

**输入表**：
- `internal_platform_db.dwd_t_event_log_v1_05900072467_with_subpartition_hi_prestosql_003`（IM平台Q群离线报告原始日志）
  - `databus_imp_date` STRING — 数据日期
  - `ftime` STRING — 时间
  - `appid` STRING — 应用ID
  - `message_id` STRING — 消息ID
  - `reqbody` STRING — 请求体(JSON)
  - `content` STRING — 内容
  - `model_id` STRING — 模型ID
  - `group_num` STRING — 群号
  - `punish_path_name` STRING — 处罚路径名称
  - `ext_field1` STRING — 扩展字段1
  - `ext_field2` STRING — 扩展字段2
  - `ds` BIGINT — 分区字段

**过滤条件**：
- `appid = '100553'`
- `reqbody IS NOT NULL`
- `get_json_object(reqbody, '$.tag_info') IS NOT NULL`
- `get_json_object(reqbody, '$.tag_info.tag_result_text') LIKE '%诈骗-%'`
- `ftime = '20250324'`

**输出要求**：
- 目标表: `internal_platform_db.dwd_qqgroup_offline_report_cand_prestosql_003`
- 输出字段及顺序: `ftime` STRING, `appid` STRING, `model_id` STRING, `message_id` STRING, `databus_imp_date` STRING, `group_num` STRING, `punish_path_name` STRING, `content` STRING
- appid 固定值 '101069'
- model_id 固定值 'IM平台Qgroup_zhapian_report_1049'
- 如果目标表不存在，请先建表再写入数据
- 请使用Presto/Trino SQL语法，不要使用Hive/Spark SQL方言
- 注意：Presto中使用json_extract_scalar代替get_json_object

**环境与执行说明**：
- Presto已启动，通过Hive catalog连接
- 执行SQL: `presto-cli --catalog hive --schema internal_platform_db -f /tmp_workspace/result.sql`
- 写出result.sql后，必须自己执行验证它能成功运行并产出正确数据

## Reference Solution
INSERT OVERWRITE TABLE internal_platform_db.dwd_qqgroup_offline_report_prestosql_003
SELECT
  ftime,
  '101069' AS appid,
  'IM平台Qgroup_zhapian_report_1049' AS model_id,
  message_id,
  databus_imp_date,
  group_num,
  punish_path_name,
  content
FROM internal_platform_db.dwd_t_event_log_v1_05900072467_with_subpartition_hi_prestosql_003
WHERE appid = '100553'
  AND reqbody IS NOT NULL
  AND get_json_object(reqbody, '$.tag_info') IS NOT NULL
  AND get_json_object(reqbody, '$.tag_info.tag_result_text') LIKE '%诈骗-%'
  AND ftime = '20250324'
# 小说UDS算法书籍关系筛选 (PrestoSQL)

## Prompt
**任务目标**：从小说UDS算法书籍关系表中，筛选指定事件类型的记录，根据事件类型映射为操作类型，提取关键字段写入输出表。

**输入表**：
- `internal_platform_db.t_oh_novel_uds_algorithm_book_rel_prestosql_004`（小说UDS算法书籍关系表）
  - `ftime` STRING — 时间
  - `event_code` STRING — 事件编码
  - `book_id` STRING — 书籍ID
  - `guid` STRING — 用户标识
  - `reqid` STRING — 请求ID
  - `traceid` STRING — 追踪ID
  - `report_time` STRING — 上报时间
  - `ds` BIGINT — 分区字段

**过滤条件**：
- `ds = 2026060906`
- `length(book_id) = 10`
- `event_code IN ('expose', 'click', 'real_read', 'add_0', 'add_1', 'shelf_add', 'share', 'comment', 'like')`

**输出要求**：
- 目标表: `internal_platform_db.t_od_novel_user_action_detail_cand_prestosql_004`
- 输出字段及顺序: `reqid` STRING, `guid` STRING, `bookid` STRING, `traceid` STRING, `action` STRING, `ftime` STRING, `report_time` STRING
- action: CASE event_code WHEN 'expose' THEN 'expose' WHEN 'click' THEN 'click' WHEN 'real_read' THEN 'real_read' WHEN 'add_0' THEN 'add_0' WHEN 'add_1' THEN 'add_1' ELSE event_code END
- bookid: book_id
- traceid: substr(traceid, 1, 4)
- 如果目标表不存在，请先建表再写入数据
- 请使用Presto/Trino SQL语法，不要使用Hive/Spark SQL方言

**环境与执行说明**：
- Presto已启动，通过Hive catalog连接
- 执行SQL: `presto-cli --catalog hive --schema internal_platform_db -f /tmp_workspace/result.sql`
- 写出result.sql后，必须自己执行验证它能成功运行并产出正确数据

## Reference Solution
INSERT OVERWRITE TABLE internal_platform_db.t_od_novel_user_action_detail_prestosql_004
SELECT
  reqid,
  guid,
  book_id AS bookid,
  substr(traceid, 1, 4) AS traceid,
  CASE event_code
    WHEN 'expose' THEN 'expose'
    WHEN 'click' THEN 'click'
    WHEN 'real_read' THEN 'real_read'
    WHEN 'add_0' THEN 'add_0'
    WHEN 'add_1' THEN 'add_1'
    ELSE event_code
  END AS action,
  ftime,
  report_time
FROM internal_platform_db.t_oh_novel_uds_algorithm_book_rel_prestosql_004
WHERE ds = 2026060906
  AND length(book_id) = 10
  AND event_code IN ('expose', 'click', 'real_read', 'add_0', 'add_1', 'shelf_add', 'share', 'comment', 'like')
# Report WUID Detail Filtering (PrestoSQL)

## Prompt
**Task Objective**: From the ad report WUID detail wide table, filter target ad delivery records based on multi-dimensional filter conditions, extract key fields, and write the results to the output table.

**Input Table**:
- `internal_platform_db.t_report_wuid_detail_d_prestosql_008` (report WUID detail table)
  - `wuid` STRING — user identifier
  - `product_id` STRING — product ID
  - `adgroup_id` BIGINT — ad group ID
  - `action_time` BIGINT — action time
  - `crm_id` BIGINT — CRM ID
  - `creative_id` BIGINT — creative ID
  - `ocpx_conversion_cnt` BIGINT — oCpx conversion count
  - `optimization_goal` INT — optimization goal
  - `second_optimization_goal` INT — second-level optimization goal
  - `roi_goal` INT — ROI goal
  - `product_type` INT — product type
  - `site_set` INT — site set
  - `crm_advertiser_industry_id` BIGINT — CRM advertiser industry ID
  - `label` INT — label
  - `partition_time` BIGINT — partition time
  - `ds` BIGINT — partition field

**Filter Conditions**:
- `partition_time = 20260608`
- `ocpx_conversion_cnt = 0`
- `optimization_goal IN (105, 603)`
- `second_optimization_goal = 0`
- `roi_goal = 7`
- `product_type = 46`
- `site_set = 21`
- `product_id IS NOT NULL`
- `crm_advertiser_industry_id != 0`
- `creative_id != 0`

**Output Requirements**:
- Target table: `internal_platform_db.sdk_sample_pay_neg_mini_cand_prestosql_008`
- Output fields and order: `wuid` STRING, `product_id` STRING, `adgroup_id` BIGINT, `action_time` BIGINT, `crm_id` BIGINT, `creative_id` BIGINT, `label` INT, `product_type` INT, `optimization_goal` INT, `roi_goal` INT, `partition_time` BIGINT
- If the target table does not exist, first create the table, then write the data
- Use Presto/Trino SQL syntax; do not use Hive/Spark SQL dialects

**Environment and Execution Notes**:
- Presto is running, connected via the Hive catalog
- Execute SQL: `presto-cli --catalog hive --schema internal_platform_db -f /tmp_workspace/result.sql`
- After writing `result.sql`, you must execute it yourself to verify that it runs successfully and produces correct data

## Reference Solution
INSERT OVERWRITE TABLE internal_platform_db.sdk_sample_pay_neg_mini_prestosql_008
SELECT
  wuid,
  product_id,
  adgroup_id,
  action_time,
  crm_id,
  creative_id,
  label,
  product_type,
  optimization_goal,
  roi_goal,
  partition_time
FROM internal_platform_db.t_report_wuid_detail_d_prestosql_008
WHERE partition_time = 20260608
  AND ocpx_conversion_cnt = 0
  AND optimization_goal IN (105, 603)
  AND second_optimization_goal = 0
  AND roi_goal = 7
  AND product_type = 46
  AND site_set = 21
  AND product_id IS NOT NULL
  AND crm_advertiser_industry_id != 0
  AND creative_id != 0
# IOC MTTD指标计算 (PrestoSQL)

## Prompt
**任务目标**：从API指标表和威胁情报IOC表中，通过JSON解析提取IOC值，与IOC表关联计算MTTD（平均检测时间）指标，写入输出表。

**输入表**：
- `internal_platform_db.t_app_ti_entity_api_metrics_prod_hi_prestosql_010`（API指标表）
  - `timestamp` BIGINT — 时间戳
  - `username` STRING — 用户名
  - `appid` BIGINT — 应用ID
  - `path` STRING — 路径
  - `request` STRING — 请求体(JSON)
  - `response` STRING — 响应体
  - `ds` BIGINT — 分区字段

- `internal_platform_db.t_sh_threat_intel_lab_breakingti_soc_endpoint_security_format_output_prod_prestosql_010`（威胁情报IOC表）
  - `ioctype` STRING — IOC类型
  - `ioc` STRING — IOC值
  - `port` STRING — 端口
  - `producer` STRING — 生产者
  - `stamp` STRING — 时间戳
  - `category` STRING — 分类
  - `family` STRING — 家族
  - `apt_org` STRING — APT组织
  - `weapon` STRING — 武器
  - `usefor` STRING — 用途
  - `ttps` STRING — TTPs
  - `confidence` INT — 置信度
  - `context` STRING — 上下文
  - `intelligence_investigation` STRING — 情报调查
  - `match_subdomains` INT — 匹配子域名
  - `bdelete` INT — 删除标记
  - `deleted_time` STRING — 删除时间
  - `first_occur_time` STRING — 首次出现时间
  - `last_occur_time` STRING — 最后出现时间
  - `ds` BIGINT — 分区字段

**计算逻辑**：
1. 从API指标表提取: json_extract_scalar(request, '$.entity_value') AS ioc_value, 按ioc_value分组取MIN(timestamp) AS earliest_timestamp, 过滤ds=20260608
2. 从IOC表过滤: ioctype='DOMAIN' AND bdelete=0, 过滤ds=20260608
3. JOIN条件: ioc = ioc_value
4. time_diff_days = GREATEST(0, (unix_timestamp(first_occur_time) - earliest_timestamp) / 86400.0)

**输出要求**：
- 目标表: `internal_platform_db.t_app_breaking_ti_mttd_metric_cand_prestosql_010`
- 输出字段及顺序: `IOC` STRING, `IOCTYPE` STRING, `PORT` STRING, `first_occur_time` STRING, `earliest_timestamp` BIGINT, `family` STRING, `match_subdomains` INT, `time_diff_days` DOUBLE, `ds` BIGINT
- ds: 固定值 20260608
- 注意Presto中用json_extract_scalar代替get_json_object，用to_unixtime代替unix_timestamp（需配合FROM_UNIXTIME相关的转换）
- 如果目标表不存在，请先建表再写入数据
- 请使用Presto/Trino SQL语法，不要使用Hive/Spark SQL方言

**环境与执行说明**：
- Presto已启动，通过Hive catalog连接
- 执行SQL: `presto-cli --catalog hive --schema internal_platform_db -f /tmp_workspace/result.sql`
- 写出result.sql后，必须自己执行验证它能成功运行并产出正确数据

## Reference Solution
INSERT OVERWRITE TABLE internal_platform_db.t_app_breaking_ti_mttd_metric_prestosql_010
WITH api_metrics AS (
  SELECT
    get_json_object(request, '$.entity_value') AS ioc_value,
    MIN(`timestamp`) AS earliest_timestamp
  FROM internal_platform_db.t_app_ti_entity_api_metrics_prod_hi_prestosql_010
  WHERE ds = 20260608
  GROUP BY get_json_object(request, '$.entity_value')
),
filtered_main AS (
  SELECT *
  FROM internal_platform_db.t_sh_threat_intel_lab_breakingti_soc_endpoint_security_format_output_prod_prestosql_010
  WHERE ioctype = 'DOMAIN' AND bdelete = 0 AND ds = 20260608
)
SELECT
  f.ioc AS IOC,
  f.ioctype AS IOCTYPE,
  f.port AS PORT,
  f.first_occur_time,
  a.earliest_timestamp,
  f.family,
  f.match_subdomains,
  GREATEST(0, (unix_timestamp(f.first_occur_time) - a.earliest_timestamp) / 86400.0) AS time_diff_days,
  20260608 AS ds
FROM filtered_main f
JOIN api_metrics a ON f.ioc = a.ioc_value
# 代码review的note diff按天同步到DWV层 (PySpark)

## Prompt
我需要你生成一段 PySpark 代码，按天把代码评审场景下"代码 note 的 diff 文件明细"从 ODS 层同步到 DWV 层。

**业务背景与目标**：上游 databus 每天会落一份当天产生的 note diff 明细到 ods 表（每行 = 一条 note 评论 + 它附带的 diff 文本）。下游 DWV 层希望按 year/month/day 三级日期分区组织，方便日期回溯，且要对一天内出现的重复行（同一个 note id 配同一段 diff 文本）做去重。

**输入表**：
- `internal_platform_db.case5_ods_code_v2_note_diff_files_diff_v3`

**数据范围与过滤条件（业务说法）**：
- 只取业务日期等于本次运行日期 ds 的数据。
- ds 固定为 '20260513'（沙箱化日期，原任务通过 sys.argv[1] 传入；TaskType=63 不传命令行参数，所以硬编码避免 IndexError）。

**表关联关系**：
（无 Join，单表抽取。）

**聚合与计算规则（需体现在 SQL 中）**：
- 直接 SELECT id, diff 两列，并做 DISTINCT 去重（同一天内同 id 同 diff 只保留一条）。
- 在 SELECT 头部追加三列分区字段，由 ds 拆分得到：year='2026'、month='05'、day='13'。
- 使用 INSERT OVERWRITE TABLE 全表覆盖写入。

**输出要求**：
- 目标表：`internal_platform_db.case5_dwv_code_v2_note_diff_files_diff_v3`
- 输出表 schema（按此顺序写入，类型与业务含义如下）：
  1. year STRING：年，原为分区列
  2. month STRING：月，原为分区列
  3. day STRING：日，原为分区列
  4. id BIGINT：note id
  5. diff STRING：diff 文本内容
- 写入策略：INSERT OVERWRITE 全表覆盖，本次写入 year='2026', month='05', day='13'。
- 沙箱化说明：原任务在生产环境写 PARTITION(year, month, day) 分区表；沙箱版三列分区列已沙箱化为普通列。
- 如果目标表不存在，请先按 Hive 标准建表（ORC 存储），再写入数据。

## Reference Solution
#!/usr/bin/env bash
from __future__ import print_function

import re
import sys
import os
import json

import datetime

from pyspark.sql import SparkSession

if __name__ == "__main__":

    print('PythonSQL start')
    #yyyyMMdd
    ds = '20260513'  # was: sys.argv[1]
    match = re.match(r"([\d]{4})([\d]{2})([\d]{2})", ds)
    daySub = match.group(1, 2, 3)

    ds_year = daySub[0]
    ds_month = daySub[1]
    ds_day = daySub[2]

    last_day = datetime.datetime(
        int(daySub[0]), int(daySub[1]), int(daySub[2]))
    last_day_str = last_day.strftime('%Y%m%d')

    print('last_day_str=%s' % last_day_str)
    print('ds_year=%s' % ds_year)
    print('ds_month=%s' % ds_month)
    print('ds_day=%s' % ds_day)

    spark = SparkSession.builder.appName('case5_dwv_code_v2_note_diff_files_diff_d_f').enableHiveSupport().getOrCreate()

    # 确保输出表以正确 schema 存在（agent 可能未建表或建了错误 schema）
    spark.sql("DROP TABLE IF EXISTS internal_platform_db.case5_dwv_code_v2_note_diff_files_diff_v3")
    spark.sql('''
CREATE TABLE internal_platform_db.case5_dwv_code_v2_note_diff_files_diff_v3 (
    `year` STRING COMMENT '年，原为分区列',
    `month` STRING COMMENT '月，原为分区列',
    `day` STRING COMMENT '日，原为分区列',
    `id` BIGINT COMMENT '-',
    `diff` STRING COMMENT '-'
) STORED AS ORC
''')

    sql = '''
            insert overwrite table internal_platform_db.case5_dwv_code_v2_note_diff_files_diff_v3
            SELECT
                    DISTINCT
                    '$year' AS year, '$month' AS month, '$day' AS day, id ,diff
            FROM internal_platform_db.case5_ods_code_v2_note_diff_files_diff_v3 where databus_imp_date='$ds'
        '''

    sql = sql.replace('$ds', last_day_str)
    sql = sql.replace('$year', ds_year)
    sql = sql.replace('$month', ds_month)
    sql = sql.replace('$day', ds_day)

    print(sql)
    result = spark.sql(sql)
    print(result.show())
    spark.stop()
# 项目管理工具PM工单变更去重 (PySpark)

## Prompt
我需要你生成一段 PySpark 代码，将 项目管理工具PM 工单变更明细表做去重处理后写入 DWV 层。

**业务背景**：上游 ODS 表 ods_pmtool_v_workitem_changes_df 按 databus_imp_date 分区存储 项目管理工具PM 工单的每次变更记录。同一个工单变更 ID 可能存在多条变更记录（如同一条 id 在不同时间点被多次修改），需要按 id 分组去重，保留最新的 workspace_id/workitem_id/workitem_type_id 等数值字段，以及最早的 creator/created/change_summary 等字符串字段，最终写入 DWV 汇总层供下游使用。

**输入表**：
- `internal_platform_db.ods_pmtool_v_workitem_changes_df_pyspark_245`

**数据范围**：只取 databus_imp_date = '20260513' 分区的数据。

**计算规则**：
1. 按 id 分组 GROUP BY
2. workspace_id、workitem_id、workitem_type_id 取 max（最新值）
3. creator、created、change_summary、comment、changes、entity_type、change_type 取 first（最早值）
4. _srcinstanceid、_srcdatabasename 输出空字符串

**输出要求**：
- 目标表：`internal_platform_db.dwv_pmtool_workitem_changes_df_pyspark_245`
- 分区：year='2026', month='05', day='13'
- 写入策略：INSERT OVERWRITE TABLE ... PARTITION(year='2026', month='05', day='13')
- 如果目标表不存在，请先按 Hive 标准建表（ORC 存储 + 分区），再写入数据。

## Reference Solution
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""pyspark_010: 项目管理工具PM workitem changes DWV - GROUP BY dedup + partition write"""

from pyspark.sql import SparkSession

spark = SparkSession.builder \
    .appName('dwv_pmtool_workitem_changes_df') \
    .enableHiveSupport() \
    .getOrCreate()

ds = '20260513'
ds_year = '2026'
ds_month = '05'
ds_day = '13'

# 输出表 DDL
spark.sql("DROP TABLE IF EXISTS internal_platform_db.dwv_pmtool_workitem_changes_df_pyspark_245")
spark.sql('''
CREATE TABLE internal_platform_db.dwv_pmtool_workitem_changes_df_pyspark_245 (
  `id` STRING,
  `workspace_id` BIGINT,
  `workitem_id` BIGINT,
  `workitem_type_id` BIGINT,
  `creator` STRING,
  `created` STRING,
  `change_summary` STRING,
  `comment` STRING,
  `changes` STRING,
  `entity_type` STRING,
  `change_type` STRING,
  `_srcinstanceid` STRING,
  `_srcdatabasename` STRING
)
PARTITIONED BY (`year` STRING, `month` STRING, `day` STRING)
STORED AS ORC
''')

sql = '''
    WITH workitem_changes AS (
        SELECT * FROM internal_platform_db.ods_pmtool_v_workitem_changes_df_pyspark_245
        WHERE databus_imp_date = '20260513'
    )
    INSERT OVERWRITE TABLE internal_platform_db.dwv_pmtool_workitem_changes_df_pyspark_245
    PARTITION(year='2026', month='05', day='13')
    SELECT
        `id`, max(`workspace_id`) AS workspace_id,
        max(`workitem_id`) AS workitem_id,
        max(`workitem_type_id`) AS workitem_type_id,
        first(`creator`) AS creator,
        first(`created`) AS created,
        first(`change_summary`) AS change_summary,
        first(`comment`) AS comment,
        first(`changes`) AS changes,
        first(`entity_type`) AS entity_type,
        first(`change_type`) AS change_type,
        '' AS _srcinstanceid,
        '' AS _srcdatabasename
    FROM workitem_changes
    GROUP BY id
'''

print(sql)
result = spark.sql(sql)
print(result.show())
spark.stop()
# Word Frequency Tumbling Window Statistics (FlinkSQL)

## Prompt
I need you to write a Flink SQL that uses a datagen built-in table to simulate a word frequency data stream, groups by `word` and opens a 1-minute tumbling window to count the occurrences of each word, and outputs the results to the console.

**Business Background and Objective**: Simulate a word frequency data stream using a datagen built-in table, generating 1 billion records in the `word` field. Use `LOCALTIMESTAMP` as the event time and set a 5-second watermark delay. Group by `word` and count the occurrences of each word over a 1-minute tumbling window, then output `word` and `cnt` to the console table.

**Source Table Definition**:
- `word_source` (word frequency stream, datagen connector):
  - `word VARCHAR`: Word, randomly generated (value range 1–1000 to simulate distinct words)
  - `event_time`: Uses `LOCALTIMESTAMP` to generate event time, with a WATERMARK delay of 5 seconds
  - Generation rate: `rows-per-second = 1000`

**Output Table Definition**:
- `console_output` (print connector):
  - `word VARCHAR`: Word
  - `cnt BIGINT`: Number of occurrences of the word within the current window

**Aggregation Logic**:
- Group by `word`, using a 1-minute tumbling window
- Aggregation metric: `COUNT(*) AS cnt`
- The window is defined by the `TUMBLE` function

**Output Requirements**:
- Use `INSERT INTO console_output` to output the results.
- Output field order: `word`, `cnt`

## Reference Solution
-- online_003: 词频滚动窗口统计
-- 单源生成 10 亿条数据 @ 1000 rows/sec

-- 1. 词频流 datagen 源表
CREATE TABLE word_source (
    word VARCHAR,
    event_time AS LOCALTIMESTAMP,
    WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND
) WITH (
    'connector' = 'datagen',
    'rows-per-second' = '1000',
    'fields.word.kind' = 'random',
    'fields.word.length' = '5'
);

-- 2. Console 输出表
CREATE TABLE console_output (
    word VARCHAR,
    cnt BIGINT
) WITH (
    'connector' = 'print'
);

-- 3. Tumble 1min 窗口词频统计
INSERT INTO console_output
SELECT
    word,
    COUNT(*) AS cnt
FROM word_source
GROUP BY TUMBLE(event_time, INTERVAL '1' MINUTE), word;
# 滚动窗口 TopN 商品排行 (FlinkSQL)

## Prompt
我需要你写一段 Flink SQL，用 datagen 内置表模拟电商订单，按 10 秒滚动窗口做 Top-N 商品排行，输出销售额最高的前 3 个商品到 console。

**业务背景与目标**：用 datagen 内置表生成电商订单（字段 order_id / product_id / amount），每秒生成约 10 条。以 LOCALTIMESTAMP 作为事件时间，设置 5 秒的 Watermark 延迟。

按 10 秒滚动窗口做 Top-N 排行：每个窗口内统计每个商品的销售额 SUM(amount) 和订单数 COUNT(*)，按销售额降序取前三名，打印到 console。

**源表定义**：
- `orders_source`（订单流，datagen 连接器）：
  - order_id BIGINT：订单 ID，随机取值 1~1000000
  - product_id INT：商品 ID，随机取值 1~1000
  - amount DOUBLE：订单金额，随机取值 1~10000
  - event_time：使用 LOCALTIMESTAMP 生成事件时间，设置 WATERMARK 延迟 5 秒
  - 生成速率：rows-per-second = 10

**输出表定义**：
- `console_output`（print 连接器）：
  - window_start TIMESTAMP(3)：窗口起始时间
  - product_id INT：商品 ID
  - sales DOUBLE：该窗口内销售额
  - order_cnt BIGINT：该窗口内订单数
  - rn BIGINT：排名序号

**TopN 逻辑**：
- 使用 10 秒滚动窗口聚合：SUM(amount) AS sales, COUNT(*) AS order_cnt
- 在窗口内使用 ROW_NUMBER() 按销售额降序排名
- 只输出排名前 3 的记录（rn <= 3）

**输出要求**：
- 使用 INSERT INTO console_output 将 Top 3 结果输出
- 输出字段顺序：window_start, product_id, sales, order_cnt, rn

## Reference Solution
-- online_005: 滚动窗口 TopN 商品排行
-- 单源生成 @ 10 rows/sec, Tumble 10s + ROW_NUMBER Top3

-- 1. 订单流 datagen 源表
CREATE TABLE orders_source (
    order_id BIGINT,
    product_id INT,
    amount DOUBLE,
    event_time AS LOCALTIMESTAMP,
    WATERMARK FOR event_time AS event_time - INTERVAL '5' SECOND
) WITH (
    'connector' = 'datagen',
    'rows-per-second' = '10',
    'fields.order_id.kind' = 'random',
    'fields.order_id.min' = '1',
    'fields.order_id.max' = '1000000',
    'fields.product_id.kind' = 'random',
    'fields.product_id.min' = '1',
    'fields.product_id.max' = '1000',
    'fields.amount.kind' = 'random',
    'fields.amount.min' = '1',
    'fields.amount.max' = '10000'
);

-- 2. Console 输出表
CREATE TABLE console_output (
    window_start TIMESTAMP(3),
    product_id INT,
    sales DOUBLE,
    order_cnt BIGINT,
    rn BIGINT
) WITH (
    'connector' = 'print'
);

-- 3. Tumble 10s 窗口聚合 + ROW_NUMBER Top 3
INSERT INTO console_output
SELECT
    window_start,
    product_id,
    sales,
    order_cnt,
    rn
FROM (
    SELECT
        TUMBLE_START(event_time, INTERVAL '10' SECOND) AS window_start,
        product_id,
        SUM(amount) AS sales,
        COUNT(*) AS order_cnt,
        ROW_NUMBER() OVER (
            PARTITION BY TUMBLE_START(event_time, INTERVAL '10' SECOND)
            ORDER BY SUM(amount) DESC
        ) AS rn
    FROM orders_source
    GROUP BY TUMBLE(event_time, INTERVAL '10' SECOND), product_id
)
WHERE rn <= 3;