SQL-分组求和

由下图SQL-分组求和_第1张图片
转换成

SQL-分组求和_第2张图片

步骤1:创建数据
CREATE TABLE F0824 (
姓名 VARCHAR(20),
今日金额 NUMERIC(18,2),
本周金额 NUMERIC(18,2),
本月金额 NUMERIC(18,2),
分组 INT
);

INSERT INTO F0824 VALUES('张三',100,900,2700,1);
INSERT INTO F0824 VALUES('李四',120,680,2900,1);
INSERT INTO F0824 VALUES('王五',110,850,3000,2);
INSERT INTO F0824 VALUES('马六',120,790,2800,2);
步骤2:code
select 姓名, 今日金额, 本周金额, 本月金额
from 
(
    select 姓名,
    sum(今日金额) as 今日金额,
    sum(本周金额) as 本周金额,
    sum(本月金额) as 本月金额,
    分组
    from F0824 group by 姓名,分组
    union all
    select rtrim(分组) + '组',
    sum(今日金额) as 今日金额,
    sum(本周金额) as 本周金额,
    sum(本月金额) as 本月金额,
    分组
    from F0824 group by rtrim(分组) + '组', 分组
    union all
    select '总计',
    sum(今日金额) as 今日金额,
    sum(本周金额) as 本周金额,
    sum(本月金额) as 本月金额,
    10000
    from F0824   
) t
order by t.分组, 姓名 desc;

你可能感兴趣的:(MySQL函数,sql,数据库,mysql)