# Low-Value Task Benefit Aggregation Statistics by Application Group (MySQL)

## Prompt
Task Objective: Summarize the current day's actual and estimated benefit metrics for low-value tasks, grouped by planning product, operations product, OBS product, and application group dimensions.

**Business Background and Objective**: Low-value task governance requires summarizing the current day's actual benefits (task count, runtime, CPU, memory) and estimated benefits (task count, runtime, CPU, memory) at the application group level to evaluate governance effectiveness. This task groups the detail data from the specified partition of the input table by four dimension fields, applies SUM aggregation to all metric fields, and writes the results to the output table.

**Input Table (full name + brief description)**:
- `internal_platform_db.dws_low_value_task_compute_statistics_day_mysql_011` (low-value task compute benefit detail daily table)

(Please connect to the database and query to confirm the table structure and field semantics.)

**Processing Rules**:
- No joins, single-table processing
- Filter condition: `dt = '20260507'`
- Aggregation logic: Group by `plan_product_name`, `obs_product_name`, `product_name`, `dw_appgroup`, applying SUM to all metric fields (`actural_task_count`, `actural_time_sum_hour`, `actural_vcore_sum_vcore_hour`, `actural_memory_sum_gb_hour`, `estimated_task_count`, `estimated_time_sum_hour`, `estimated_vcore_sum_vcore_hour`, `estimated_memory_sum_gb_hour`)

**Output Requirements**:
- Target table: `internal_platform_db.dws_low_value_task_compute_appgroup_stats_day_cand_mysql_011`
- Output field order: `dt`, `plan_product_name`, `obs_product_name`, `product_name`, `dw_appgroup`, `actural_task_count`, `actural_time_sum_hour`, `actural_vcore_sum_vcore_hour`, `actural_memory_sum_gb_hour`, `estimated_task_count`, `estimated_time_sum_hour`, `estimated_vcore_sum_vcore_hour`, `estimated_memory_sum_gb_hour`
- `dt` field value: `'20260507'`
- Types: `dt` VARCHAR(8), `plan_product_name` VARCHAR(256), `obs_product_name` VARCHAR(256), `product_name` VARCHAR(256), `dw_appgroup` VARCHAR(256), `actural_task_count` INT, `actural_time_sum_hour` DOUBLE, `actural_vcore_sum_vcore_hour` DOUBLE, `actural_memory_sum_gb_hour` DOUBLE, `estimated_task_count` INT, `estimated_time_sum_hour` DOUBLE, `estimated_vcore_sum_vcore_hour` DOUBLE, `estimated_memory_sum_gb_hour` DOUBLE
- If the target table does not exist, first create it using standard MySQL InnoDB format, then write the data
- Use standard MySQL syntax; do not use Hive/Spark SQL dialects (e.g., `INSERT OVERWRITE`, `STORED AS ORC`, `PARTITIONED BY` are not supported)
- Write method: Use `INSERT INTO ... SELECT ...` statements

**Environment and Execution Notes**:
- Your final output must be written to the file `/tmp_workspace/result.py`, not `result.sql`
- The local MySQL is running at localhost:3306, username `root`, password `root123`
- Use Python `pymysql` in `result.py` to execute the SQL (do not use the `mysql` command-line tool)
- The script must include complete table creation (if the target table does not exist) and data writing logic
- After writing `result.py`, you must execute `python3 /tmp_workspace/result.py` yourself to verify that it runs successfully and produces correct data

## Reference Solution
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
mysql_011 ground truth: 低价值任务收益按应用组聚合统计

Task:
  Filter input table WHERE dt = '20260507',
  GROUP BY plan_product_name, obs_product_name, product_name, dw_appgroup,
  SUM all metric fields, write to output table with dt = '20260507'.
"""
import pymysql
import sys

DB_NAME = "internal_platform_db"
INPUT_TABLE = "dws_low_value_task_compute_statistics_day_mysql_011"
OUTPUT_TABLE = "dws_low_value_task_compute_appgroup_stats_day_cand_mysql_011"

MYSQL_CONFIG = {
    "host": "localhost",
    "port": 3306,
    "user": "root",
    "password": "root123",
    "charset": "utf8mb4",
}

gt_sql = f"""
INSERT INTO {DB_NAME}.{OUTPUT_TABLE}
    (dt, plan_product_name, obs_product_name, product_name, dw_appgroup,
     actural_task_count, actural_time_sum_hour, actural_vcore_sum_vcore_hour,
     actural_memory_sum_gb_hour, estimated_task_count, estimated_time_sum_hour,
     estimated_vcore_sum_vcore_hour, estimated_memory_sum_gb_hour)
SELECT
    '20260507' AS dt,
    plan_product_name,
    obs_product_name,
    product_name,
    dw_appgroup,
    SUM(actural_task_count) AS actural_task_count,
    SUM(actural_time_sum_hour) AS actural_time_sum_hour,
    SUM(actural_vcore_sum_vcore_hour) AS actural_vcore_sum_vcore_hour,
    SUM(actural_memory_sum_gb_hour) AS actural_memory_sum_gb_hour,
    SUM(estimated_task_count) AS estimated_task_count,
    SUM(estimated_time_sum_hour) AS estimated_time_sum_hour,
    SUM(estimated_vcore_sum_vcore_hour) AS estimated_vcore_sum_vcore_hour,
    SUM(estimated_memory_sum_gb_hour) AS estimated_memory_sum_gb_hour
FROM {DB_NAME}.{INPUT_TABLE}
WHERE dt = '20260507'
GROUP BY plan_product_name, obs_product_name, product_name, dw_appgroup
"""


def main():
    conn = pymysql.connect(**MYSQL_CONFIG)

    try:
        with conn.cursor() as cur:
            # Ensure output table exists
            cur.execute(f"""
                CREATE TABLE IF NOT EXISTS {DB_NAME}.{OUTPUT_TABLE} (
                    dt                              VARCHAR(8)    NOT NULL COMMENT '天级分区',
                    plan_product_name               VARCHAR(256)  DEFAULT NULL COMMENT '规划产品名',
                    obs_product_name                VARCHAR(256)  DEFAULT NULL COMMENT '运营产品名',
                    product_name                    VARCHAR(256)  DEFAULT NULL COMMENT 'OBS产品名',
                    dw_appgroup                    VARCHAR(256)  DEFAULT NULL COMMENT '应用组',
                    actural_task_count              INT           DEFAULT NULL COMMENT '实际收益-任务数',
                    actural_time_sum_hour           DOUBLE        DEFAULT NULL COMMENT '实际收益-运行时间(hour)',
                    actural_vcore_sum_vcore_hour    DOUBLE        DEFAULT NULL COMMENT '实际收益-CPU(vcore*hour)',
                    actural_memory_sum_gb_hour      DOUBLE        DEFAULT NULL COMMENT '实际收益-内存(gb*hour)',
                    estimated_task_count            INT           DEFAULT NULL COMMENT '预估收益-任务数',
                    estimated_time_sum_hour         DOUBLE        DEFAULT NULL COMMENT '预估收益-运行时间(hour)',
                    estimated_vcore_sum_vcore_hour  DOUBLE        DEFAULT NULL COMMENT '预估收益-CPU(vcore*hour)',
                    estimated_memory_sum_gb_hour     DOUBLE        DEFAULT NULL COMMENT '预估收益-内存(gb*hour)'
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
            """)

            # Truncate + insert
            cur.execute(f"TRUNCATE TABLE {DB_NAME}.{OUTPUT_TABLE}")
            cur.execute(gt_sql)

        conn.commit()
        print("mysql_011 ground_truth done: 12 rows written to output table")
    except Exception as e:
        print(f"ground_truth error: {e}", file=sys.stderr)
        conn.rollback()
        sys.exit(1)
    finally:
        conn.close()


if __name__ == "__main__":
    main()