2017-04-04 58 views
0

我有2个表,想要从2个表中获得行总和 结果是这样的例如sh2:19 + 5 + 11 + 5 = 40为每个名称计算它们所有表中的 我使用该代码sql coalesce chenge选择案例

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 

,但我想使用select和案例

+0

你使用MySQL或MS SQL Server的代码?不要标记不涉及的产品。 – jarlh

+1

添加示例表格数据和预期结果 - 以及格式化文本。 – jarlh

+0

@jarlh嗨你帮我一次tnx为这里是样本数据 http://stackoverflow.com/questions/43162761/sql-row-sum-with-condition-from-2-tables/43166625#43166625 – saman

回答

0
select name,SUM(total)total from(
     select name,sum(case when sk>0 then sk else ss end)total from majale group by name 
     union all 
     select name,sum(case when sk>0 then sk else ss end)from ketab group by name 
     union all 
     select name,sum(case when sk>0 then sk else ss end)from savabegh group by name 
    )t 
     group by name