2017-04-04 55 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