mysql-全表累加统计
实现思路
1)定义用户变量,设定初始值
2)累加赋值,所求值作为显示列
SELECT
create_time,total_num,@total_num := 0,
@total_num := @total_num + stn AS stn
FROM (
SELECT
create_time,total_num,sum(total_num) stn
FROM opm_merchant_coupon WHERE activity_id=4020000000220
GROUP BY create_time
order by create_time ) AS temp,(SELECT @total_num := 0) t
说明
- SELECT @total_num := 0表示初始化一个用户变量并作为临时表,之后实现类似于java中的累加操作.其中,temp和t是临时表,@total_num := 0是从临时表中取出的显示列.
- 用户变量这种实现方式适用于全表累加统计.
mysql-分组累加统计
实现思路
1)基于父查询传递的值进行范围性的子查询,然后拼接出想要的字段(子查询作为显示列)
2)父查询最终显示每一行数据
简化-示例
SELECT a, b, c,
(SELECT SUM(c) FROM sss WHERE a= A.a AND b<= A.b) t
FROM sss A;
说明
- 父查询和子查询通过a字段关联(比如id)
- 父查询第一行数据传递关联字段值到子查询,基于子查询返回组装列到第一行父查询的记录
- 以此类推,每一行父查询的记录便拼接上了累加统计字段
其它-示例
SELECT
omc.id, omc.merchant_code, omc.merchant_name, omc.user_code, omc.activity_id, omc.activity_name,omc.parklot_range_code, omc.parklot_range_name, omc.send_type, omc.buy_type, omc.forward_time,omc.rule_type,
omc.info, omc.time_type, omc.valid_start_time, omc.valid_end_time, omc.delay_time,omc.valid_time, omc.total_num, omc.remain_num, omc.create_time, omc.op_time, omc.sys_time,
sca.total_num-(SELECT SUM(total_num) FROM opm_merchant_coupon
WHERE activity_id = omc.activity_id AND create_time <= omc.create_time) couponRemainNum
FROM opm_merchant_coupon omc
left join sys_coupon_activity sca on omc.activity_id=
sca.id
where 1=1
and omc.merchant_name like CONCAT('%','大厦中心','%' )
order by omc.create_time desc
limit 0,10