Mysql累积求和

1、样例表表结构
show create table event_attractnew_daily_invitation_201805;
CREATE TABLE `event_attractnew_daily_invitation_201805` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键 ID',
  `uid` bigint(20) NOT NULL COMMENT '用户 Uid',
  `count` int(11) NOT NULL DEFAULT '0' COMMENT '邀请人数',
  `effective_count` int(11) NOT NULL DEFAULT '0' COMMENT '有效邀请人数',
  `amount` decimal(20,6) NOT NULL DEFAULT '0.000000' COMMENT '赚取金额',
  `daily_date` date NOT NULL COMMENT '日期',
  `created_time` datetime NOT NULL COMMENT '创建时间',
  `updated_time` datetime NOT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `idx_daily_uid` (`daily_date`,`uid`),
  KEY `index_amount_time` (`amount`,`created_time`)
) ENGINE=InnoDB AUTO_INCREMENT=5278 DEFAULT CHARSET=utf8mb4 COMMENT='现金拉新活动每天邀请记录表';
2、累积求和sql
select a1.daily_date,a1.uid,a1.count,a1.effective_count,sum(a2.count) accumulate_count,sum(a2.effective_count) accumulate_effective_count
from event_attractnew_daily_invitation_201805 a1
join event_attractnew_daily_invitation_201805 a2 on a1.uid=a2.uid and a1.daily_date>=a2.daily_date
group by a1.daily_date,a1.uid,a1.count,a1.effective_count
order by a1.uid,a1.daily_date;
3、说明
在Oralce及Hive上有非常方便的分析函数可以解决此类问题,但mysql就要其他途径曲线实现。
只考虑一列累积求和的样例:
CREATE TABLE cum_demo
(id INT,money INT,PRIMARY KEY (id));

insert into cum_demo(id,money)
values (1,10),(2,20),(3,30),(4.40);

SELECT a.id,a.money,SUM(lt.money)  as cum
FROM cum_demo a JOIN cum_demo lt 
ON a.id >= lt.id
GROUP BY a.money
ORDER BY id;

猜你喜欢

转载自blog.csdn.net/babyfish13/article/details/80496711
今日推荐