sum问题

AstaChen 2015-10-24 05:22:45
tmp_statement_db里的每行记录都要显示
如果mainid=0,则直接显示amount
如果mainid>0,则肯定有且只有2条记录的mainid相同。
如果mainid>0,则这些记录要把所有相同mainid的amount合计在一起后除以2

像下面的id in (3,4),他们的mainid相同,则把30+40=70,70/2=35,则3,4的amount都显示为35

测试数据如下:

DROP TEMPORARY TABLE IF EXISTS tmp_statement_db;
create temporary table tmp_statement_db(id int,title varchar(10),mainid int,amount decimal(19,2));

insert into tmp_statement_db(id,title,mainid,amount)
select 1,'a',0,10
UNION
select 2,'b',0,20
union
select 3,'c',3,30
UNION
select 4,'d',3,40;

要的结果:
id title main amount
1 a 0 10.00
2 b 0 20.00
3 c 3 35.00
4 d 3 35.00
...全文
125 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
AstaChen 2015-10-25
  • 打赏
  • 举报
回复
引用 2 楼 u011575570 的回复:
如楼上的用case when 也可以使用if else也可以的
不行啊,临时表不能引用2次,请见上贴
AstaChen 2015-10-25
  • 打赏
  • 举报
回复
引用 1 楼 ACMAIN_CHM 的回复:
select id ,title , main, case mainid when 0 then amount ELSE (select avg(amount) from tmp_statement_db where mainid=t.mainid) end from tmp_statement_db t
错误啊,是mysql啊,临时表只能引用一次 [Err] 1137 - Can't reopen table: 't'
AstaChen 2015-10-25
  • 打赏
  • 举报
回复
rick-he 2015-10-24
  • 打赏
  • 举报
回复
如楼上的用case when 也可以使用if else也可以的
ACMAIN_CHM 2015-10-24
  • 打赏
  • 举报
回复
select id ,title , main, case mainid when 0 then amount ELSE (select avg(amount) from tmp_statement_db where mainid=t.mainid) end from tmp_statement_db t

56,675

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧