SQL - Row sum with condition from 2 tables

荒凉一梦 提交于 2019-12-12 04:31:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!