--- id: online-compute_FlinkSQL_flinksql_017 name: Row-Level TopN (Windowless) category: online-compute/FlinkSQL timeout_seconds: 600 modality: pure-text engine: flink-sql --- ## Prompt I need you to write a Flink SQL that uses the built-in datagen connector to simulate a spending stream, retrieves the top 3 records by spending amount grouped by `country_id` without any window, and outputs the results directly to the console. **Business Background and Objective**: Generate user spending records using a datagen built-in table at a rate of 1000 rows per second. Fields include `country_id` (country ID, 1–30), `user_id` (user ID, 1–100,000), and `cost_money` (spending amount, 0–10,000). No event time or watermark is required, since no window operations are involved. Use the `ROW_NUMBER()` window function, partitioned by `country_id` and sorted by `cost_money` in descending order, keeping only the top 3 records per partition (`row_num <= 3`), and output the results directly to the console table. This is a continuous TopN query where each country's top 3 dynamically updates as new data flows in. **Source Table Definition**: - `spend_source` (datagen connector): - `country_id INT`: Country ID, randomly generated in the range 1–30 - `user_id INT`: User ID, randomly generated in the range 1–100,000 - `cost_money DOUBLE`: Spending amount, randomly generated in the range 0–10,000 - Generation rate: `rows-per-second = 1000` **Output Table Definition**: - `console_output` (print connector): - `country_id INT`: Country ID - `user_id INT`: User ID - `cost_money DOUBLE`: Spending amount - `row_num BIGINT`: Row number **TopN Logic**: - Use `ROW_NUMBER() OVER (PARTITION BY country_id ORDER BY cost_money DESC)` to generate row numbers - Apply `WHERE row_num <= 3` to keep the top 3 per country - No window operation is required; no event time or watermark needs to be defined **Output Requirements**: - Use `INSERT INTO console_output` to output the results. - Output field order: `country_id`, `user_id`, `cost_money`, `row_num`