如何解决如何在SQL中合并值
我想将值合并到一张表中
select sum(if(dep_id=2,point,0)) as totalpoint,sum(if(dep_id=3,0)) as totalpoint
from user_info
这是我的桌子:
我想要这样的结果:
我不知道该如何解决。请帮助我
解决方法
您似乎想要聚合:
select dep_id,sum(point) totalpoints
from user_info
where dep_id in (2,3)
group by dep_id
如果表中缺少dep_id
,而您仍然希望它们在结果集中具有0
值,则有些不同。一种选择是枚举派生表中的值,然后将原始表进行联接:
select d.dep_id,coalesce(sum(ui.point),0) totalpoints
from (select 2 dep_id union all select 3) d
left join user_info ui on ui.dep_id = d.dep_id
group by d.dep_id
,
您也可以使用UNION:
select dep_id,sum(point) as totalpoint
from user_info
where dept_id = 2
union
select dep_id,sum(point) as totalpoint
from user_info
where dept_id = 3
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。