MySQL查询如何在不修改数据库的情况下合并指定数据行为汇总新行
需求说明
当前使用的SQL为第三方编写,无数据库修改权限,仅可通过调整查询逻辑实现指定的结果合并效果:
- 原查询按消费类型
ptype聚合对应金额,输出包含home、work、away、lunch共4类格式化金额 - 目标输出规则:
home、work类保持原有结果不变,away和lunch两类的金额求和后合并为afk类,不再单独输出两个原分类行
原始查询代码
set @year = 2020; set @reportd = '###'; set @asofday = '2020-01-01'; select format(sum(x.value), 0) xvalue, x.ptype from ( select p.mnum, (p.bvalue + p.lvalue) as value, p.exeamount, p.excamount, p.damount, phis.ptype from history h join Dfee d on d.p_id = h.p_id and d.dcode = @reportd join( select max(history.id) as id, pc.ptype from history join cash c on history.id = c.p_id join pclass pc on history.pc_id = pc.id where c.year = @year and date(c.cdate) <= (select x.date from (select date(cdate) date, count(date(cdate)) A from cash where year = @year group by date(cdate) having A > 1 order by A desc limit 1) x) group by history.mnum ) phis.id = h.id) x group by x.ptype ;
原始查询输出结构:
+------------+------------+ | xvalue| ptype | +------------+------------+ | 124,213,122| home | +------------+------------+ | 223,334,552| work | +------------+------------+ | 112,112,220| away | +------------+------------+ | 154,556,454| lunch | +------------+------------+
初次尝试的问题
最初尝试在外层嵌套查询直接对原结果集做汇总,未做分类值映射,示例写法:
select SUM(xvalue) xvalue FROM ( [原查询结果] ) x GROUP BY ptype;
由于分组键还是原结果集里的away、lunch两个不同的取值,最终仍会返回两个独立行,未实现合并求和的效果:
+-------+-------+ | xvalue| ptype | +-------+-------+ | 124 | home | +-------+-------+ | 223 | work | +-------+-------+ | 112 | afk | +-------+-------+ | 154 | afk | +-------+-------+
修正后的可运行查询
核心调整逻辑:
- 在外层聚合前,用
CASE表达式对分类值做统一映射:home、work类直接保留原分类名,away、lunch类统一映射为afk - 按映射后的分类名重新做聚合求和
修正后完整代码:
set @year = 2020; set @reportd = '###'; set @asofday = '2020-01-01'; select (case when y.ptype in('work', 'home') then y.ptype else 'afk' end) ptype, format(sum(xvalue), 0) yvalue from ( select format(sum(x.value), 0) xvalue, x.ptype from ( select p.mnum, (p.bvalue + p.lvalue) as value, p.exeamount, p.excamount, p.damount, phis.ptype from history h join Dfee d on d.p_id = h.p_id and d.dcode = @reportd join( select max(history.id) as id, pc.ptype from history join cash c on history.id = c.p_id join pclass pc on history.pc_id = pc.id where c.year = @year and date(c.cdate) <= (select x.date from (select date(cdate) date, count(date(cdate)) A from cash where year = @year group by date(cdate) having A > 1 order by A desc limit 1) x) group by history.mnum ) phis.id = h.id) x group by x.ptype) y group by ptype;
修正后输出完全符合预期:
+------------+------------+ | xvalue| ptype | +------------+------------+ | 124,213,122| home | +------------+------------+ | 223,334,552| work | +------------+------------+ | 266,668,674| afk | +------------+------------+
内容的提问来源于stack exchange,提问作者Ethan Graybeal
相关产品推荐
相关产品推荐

