# 数据总线 Consumer Group Cost Detail Data Aggregation and Column Renaming (MySQL)

## Prompt
I need you to generate a MySQL script that summarizes packet count, size, and cost from 数据总线 consumer group cost raw data, grouped by consumer group + business ID + topic, to produce a consumer group cost detail table.

**Business Background and Objective**: 数据总线 periodically writes cost data for each consumer group into a raw detail table. Downstream consumers only need records from the `dt = '20260507'` partition, grouped by `business_id`, `topic`, and `consumer_group`, with MAX aggregation applied to all other fields before writing to the output table. The output field names must also match the downstream table conventions. This task aggregates qualifying records from the input table, performs column renaming, and writes to the output table.

**Input Table (full name + brief description)**:
- `internal_platform_db.ods_t_databus_consume_cost_final_date_d_mysql_009` (数据总线 consumer group cost raw data table)

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

**Filter and Aggregation Rules**:
- Filter condition: `dt = '20260507'`
- Aggregation logic: Group by `business_id`, `topic`, `consumer_group`
- Apply MAX to `systemname`, `dwproductname`, `dwappgroup`, `cityid`, `iset`, `pkgcnt`, `tubesize`, `total_cost`, and `in_charge`

**Column Renaming Rules**:
- Input column `systemname` → output column `system_belong`
- Input column `dwproductname` → output column `category_name`
- Input column `dwappgroup` → output column `dw_appgroup`
- Input column `cityid` → output column `city_id`
- Input column `iset` → output column `cluster_set`
- Input column `consumer_group` → output column `consumergroup`
- Input column `pkgcnt` → output column `pkg_cnt`
- Input column `tubesize` → output column `data_size`
- `business_id`, `topic`, `total_cost`, `in_charge` retain their original names

**Output Requirements**:
- Target table: `internal_platform_db.dwd_databus_consumergroup_cost_detail_d_cand_mysql_009`
- Table comment: 数据总线 consumer group cost detail table, performing data cleansing on the ODS table
- Output field order: `dt`, `system_belong`, `category_name`, `dw_appgroup`, `city_id`, `cluster_set`, `consumergroup`, `business_id`, `topic`, `pkg_cnt`, `data_size`, `total_cost`, `in_charge`
- Field types: `dt` VARCHAR(256), `system_belong` VARCHAR(256), `category_name` VARCHAR(256), `dw_appgroup` VARCHAR(256), `city_id` VARCHAR(256), `cluster_set` VARCHAR(256), `consumergroup` VARCHAR(256), `business_id` VARCHAR(256), `topic` VARCHAR(256), `pkg_cnt` BIGINT, `data_size` BIGINT, `total_cost` DOUBLE, `in_charge` VARCHAR(256)
- 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

**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_009 ground truth: 数据总线消费组成本明细数据聚合与列重命名

Task:
  Filter input table WHERE dt = '20260507',
  GROUP BY business_id, topic, consumer_group,
  MAX() for systemname, dwproductname, dwappgroup, cityid, iset, pkgcnt, tubesize, total_cost, in_charge,
  rename columns, write to output table.
"""
import pymysql
import sys

DB_NAME = "internal_platform_db"
INPUT_TABLE = "ods_t_databus_consume_cost_final_date_d_mysql_009"
OUTPUT_TABLE = "dwd_databus_consumergroup_cost_detail_d_cand_mysql_009"

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

gt_sql = f"""
INSERT INTO {DB_NAME}.{OUTPUT_TABLE}
    (dt, system_belong, category_name, dw_appgroup, city_id, cluster_set,
     consumergroup, business_id, topic, pkg_cnt, data_size, total_cost, in_charge)
SELECT
    '20260507'                AS dt,
    MAX(systemname)           AS system_belong,
    MAX(dwproductname)       AS category_name,
    MAX(dwappgroup)          AS dw_appgroup,
    MAX(cityid)               AS city_id,
    MAX(iset)                 AS cluster_set,
    consumer_group            AS consumergroup,
    business_id,
    topic,
    MAX(CAST(pkgcnt AS UNSIGNED))    AS pkg_cnt,
    MAX(CAST(tubesize AS UNSIGNED))  AS data_size,
    MAX(CAST(total_cost AS DOUBLE))    AS total_cost,
    MAX(in_charge)            AS in_charge
FROM {DB_NAME}.{INPUT_TABLE}
WHERE dt = '20260507'
GROUP BY business_id, topic, consumer_group
"""


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(256)  NOT NULL COMMENT '天分区',
                    system_belong   VARCHAR(256)  NOT NULL COMMENT '系统名',
                    category_name   VARCHAR(256)  NOT NULL COMMENT '数据仓库DW产品名称',
                    dw_appgroup    VARCHAR(256)  NOT NULL COMMENT '数据仓库DW应用组',
                    city_id         VARCHAR(256)  NOT NULL COMMENT '城市ID',
                    cluster_set     VARCHAR(256)  NOT NULL COMMENT '集群',
                    consumergroup   VARCHAR(256)  NOT NULL COMMENT '消费组',
                    business_id     VARCHAR(256)  NOT NULL COMMENT '业务ID',
                    topic           VARCHAR(256)  NOT NULL COMMENT 'topic',
                    pkg_cnt         BIGINT        NOT NULL COMMENT '包数',
                    data_size       BIGINT        NOT NULL COMMENT '大小',
                    total_cost      DOUBLE        NOT NULL COMMENT '总成本',
                    in_charge       VARCHAR(256)  NOT NULL COMMENT '负责人'
                ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='数据总线消费组成本明细表，ods表做数据清洗'
            """)

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

        conn.commit()
        print("mysql_009 ground_truth done: 3 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()