mysql 按条件分组累计求和

mysql 按条件分组累计求和,第1张

select (select avg(sales) from 表名 b where (a.date-b.date) between 0 and 20) as [前20日平均销量],* from 表名 a

创建表:

create table test

(date datetime,

userid varchar(2),

amount int)

insert into test values ('2018-10-02 00:00:00','u1',20)

insert into test values ('2018-10-02 21:09:28','u2',20)

insert into test values ('2018-10-02 21:09:29','u3',30)

insert into test values ('2018-10-03 21:36:44','u1',20)

insert into test values ('2018-10-03 21:36:46','u2',72)

insert into test values ('2018-10-03 21:36:52','u3',30)

insert into test values ('2018-10-30 21:36:54','u1',10)

insert into test values ('2018-10-30 21:36:57','u2',10)

执行:

select a.date,a.userid,a.amount,sum(b.amount) from test a,test b where a.userid=b.userid and a.date>=b.date group by a.date,a.userid,a.amount

结果:

1、创建三张测试表,

create table pw_memberinfo(uid int, name varchar(20))

create table pw_members(companyid int, uid int)

create table pw_memberdata(uid int, deposit int, ddeposit int, money int)

2、三张表,分别插入测试数据,

insert into pw_members values(1, 1)

insert into pw_members values(1, 2)

insert into pw_members values(1, 3)

insert into pw_memberinfo values(1, 'name_1')

insert into pw_memberinfo values(2, 'name_2')

insert into pw_memberinfo values(3, 'name_3')

insert into pw_memberdata values(1,30,50,150)

insert into pw_memberdata values(2,77,50,12)

insert into pw_memberdata values(3,44,50,82)

3、查看pw_memberdata表中的记录,select * from pw_memberdata t,

4、编写sql语句

select * from (SELECT i.uid, sum(deposit+ddeposit+money) as allmoney

FROM pw_memberinfo i

LEFT JOIN pw_members m ON m.uid=i.uid

LEFT JOIN pw_memberdata d ON i.uid=d.uid

group by i.uid

) t where allmoney>200


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/7372310.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-04
下一篇 2023-04-04

发表评论

登录后才能评论

评论列表(0条)

保存