问题
I have 2 tables and want to get the row sum from 2 tables with conditions. Here are my tables:
tabale1, tabale2
i want the row sum from 2 tables, like:
if sk not null sum sk but if it is null sk = ss
For example, the total sum of sh2 is: 19 + 5 + 11 + 5 = 40
I really need that, please help!
Table1:
Table2:
回答1:
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.
回答2:
Use coalesce to pick sk if sk is not null. Otherwise (if sk is null), ss will be used.
UNION ALL the two tables, and GROUP BY its result:
select name, sum(skss)
from
(
select name, coalesce(sk, ss) skss
from table1
union all
select name, coalesce(sk, ss) skss
from table2
) dt
group by name
来源:https://stackoverflow.com/questions/43162761/sql-row-sum-with-condition-from-2-tables