使用MySQL对相似数据分组并基于指定表结构生成报表
我来帮你整理表结构并给出适合报表需求的MySQL分组方案:
BillableDatas 表结构与现有数据
| BIL_Id | BIL_Date | BIL_Rate | BIL_Quantity | BIL_Status |
|---|---|---|---|---|
| 1 | 2018-03-01 | 105 | 2 | notcharged |
| 2 | 2018-03-01 | 30 | 2 | notcharged |
| 3 | 2018-03-02 | 115 | 2 | charged |
| 4 | 2018-03-03 | 105 | 1 | notcharged |
| 5 | 2018-03-04 | 105 | 1 | notcharged |
| 6 | 2018-03-0... | - | - | - |
MySQL 分组查询方案(用于报表生成)
针对报表需求,我们通常会把维度相同的相似数据(比如同一日期、同一费率、同一状态的记录)分组汇总,这样报表会更清晰直观。下面是具体的SQL实现:
1. 按日期、费率、状态完整分组(最细粒度)
这个方案会把所有维度完全一致的记录归为一组,统计每组的记录数、总数量和总金额,适合需要详细数据的报表:
SELECT BIL_Date, BIL_Rate, BIL_Status, COUNT(BIL_Id) AS total_records, -- 该分组下的记录条数 SUM(BIL_Quantity) AS total_quantity, -- 分组内的总服务/产品数量 SUM(BIL_Rate * BIL_Quantity) AS total_amount -- 分组内的总费用 FROM BillableDatas GROUP BY BIL_Date, BIL_Rate, BIL_Status ORDER BY BIL_Date ASC;
执行后你会得到类似这样的汇总结果(基于你提供的完整数据):
| BIL_Date | BIL_Rate | BIL_Status | total_records | total_quantity | total_amount |
|---|---|---|---|---|---|
| 2018-03-01 | 105 | notcharged | 1 | 2 | 210 |
| 2018-03-01 | 30 | notcharged | 1 | 2 | 60 |
| 2018-03-02 | 115 | charged | 1 | 2 | 230 |
| 2018-03-03 | 105 | notcharged | 1 | 1 | 105 |
| 2018-03-04 | 105 | notcharged | 1 | 1 | 105 |
2. 灵活调整分组维度
如果你的报表不需要这么细的粒度(比如只关心按日期和状态汇总),只需要修改GROUP BY的字段即可:
SELECT BIL_Date, BIL_Status, COUNT(BIL_Id) AS total_records, SUM(BIL_Quantity) AS total_quantity, SUM(BIL_Rate * BIL_Quantity) AS total_amount FROM BillableDatas GROUP BY BIL_Date, BIL_Status ORDER BY BIL_Date ASC;
这样就能得到按日期和状态汇总的报表数据,适合做趋势分析类的报表。
内容的提问来源于stack exchange,提问作者user9516731
相关产品推荐
相关产品推荐

