sql 查询出来的结果相加相减如何写?
我在sql里查询出来了结果,都是数值列的,应该如何相加?例如:selectsum(num1)fromtable1selectsum(num2)fromtable2...s...
我在sql里查询出来了结果,都是数值列的,应该如何相加?
例如:select sum(num1) from table1
select sum(num2) from table2
.
.
.
select sum(numn) from tablen
然后我要把这些结果有些加,有些要减,应该如何写语句?
需要把num1的结果加上num2和num3的结果,然后再减去num4和num5的结果,最终显示一个计算出来的值 展开
例如:select sum(num1) from table1
select sum(num2) from table2
.
.
.
select sum(numn) from tablen
然后我要把这些结果有些加,有些要减,应该如何写语句?
需要把num1的结果加上num2和num3的结果,然后再减去num4和num5的结果,最终显示一个计算出来的值 展开
2个回答
展开全部
把这些列求和后建立新的表 就是子查询了。新表的结构就是下面了
select a.snum1 + b.snum2 + c.snum3 - d.snum4 - e.snum5 from
(select sum(num1) snum1 from table1)a ,
(select sum(num2) snum2 from table2)b ,
(select sum(num3) snum3 from table3)c ,
(select sum(num4) snum4 from table4)d ,
(select sum(num5) snum5 from table5)e
select a.snum1 + b.snum2 + c.snum3 - d.snum4 - e.snum5 from
(select sum(num1) snum1 from table1)a ,
(select sum(num2) snum2 from table2)b ,
(select sum(num3) snum3 from table3)c ,
(select sum(num4) snum4 from table4)d ,
(select sum(num5) snum5 from table5)e
展开全部
减的话,这样实现:
select sum(fa) from
(
select sum(num1) as fa from table1
union
select sum(num2) as fa from table2
union
select sum(num3) as fa from table3
union
select 0-sum(num4) as fa from table4
union
select 0-sum(num5) as fa from table5
) as tmp
=====================================
=====================================
方法多种,先给一种:
select sum(fa) from
(
select sum(num1) as fa from table1
union
select sum(num2) as fa from table2
union
...
union
select sum(numn) as fa from tablen
) as tmp
select sum(fa) from
(
select sum(num1) as fa from table1
union
select sum(num2) as fa from table2
union
select sum(num3) as fa from table3
union
select 0-sum(num4) as fa from table4
union
select 0-sum(num5) as fa from table5
) as tmp
=====================================
=====================================
方法多种,先给一种:
select sum(fa) from
(
select sum(num1) as fa from table1
union
select sum(num2) as fa from table2
union
...
union
select sum(numn) as fa from tablen
) as tmp
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询