本文介绍了SQL-具有来自2个表的条件的行总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个表,并且想从2个表中获取有条件的行总和.这是我的桌子:

I have 2 tables and want to get the row sum from 2 tables with conditions.Here are my tables:

tabale1 tabale2

我想要2个表的行总和,例如:

i want the row sum from 2 tables, like:

if sk not null sum sk but if it is null sk = ss

例如,sh2的总和为:19 + 5 + 11 + 5 = 40

For example, the total sum of sh2 is: 19 + 5 + 11 + 5 = 40

我真的很需要,请帮忙!

I really need that, please help!

表1:

表2:

推荐答案

下一个sql将返回表中的总和,并按名称分组:

Next sql will return the sum over the tables, grouping by name:

select name, sum(total) total from
(select name, sum(coalesce(sk,ss)) total
 from table1
 group by name
 union all
 select name, sum(coalesce(sk,ss)) total
 from table2
 group by name
) t
group by name

子查询中的分组依据"子句非常重要,因为表是否返回很多行,它们将减少查询中分组依据"的行数,从而优化了时间并减少了内存使用.

The clause "group by" inside of the subqueries is very important because whether the tables return a lot of lines, they will reduce the number of lines for the "group by" on the query, optimizing time and using less memory.

这篇关于SQL-具有来自2个表的条件的行总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 16:52