select
id, amount - (select sum(amount) as amount
from table2
where column = 'value' and table1.id = table2.id
group by table2.id) as amount
from
table1
order by
table1.id
结果是来自table1的所有值 - 来自amount
的{{1}}除了table2
以外的table1.id
,它们都是空值。
所以这一切都很好,除了我有空值,因为我需要这些值为table2.id
值
也试过这样的东西,但仍然无法正常工作
table1.amount
然后我得到select
id, amount - isnull((select sum(amount) as amount
from table2
where column = 'value' and table1.id = table2.id
group by table2.id), table1.amount) as amount
from
table1
order by
table1.id
,但结果集中为空的0.00
确实在table1.id
我需要的概述
table1.amount
所以我需要table1 - 表2中的值来获取结果表
答案 0 :(得分:1)
更好地做到这一点
select
t1.id, t1.amount - isnull(t2.amountTable2,0) as 'amount'
from table1 T1
left join (select id, sum(ammunt) as 'amountTable2' from table2 group by Id) T2
on t1.id = t2.id
order by t1.id
这将获得Sum
中每个ID的总table2
那么join
将通过id,并发挥作用。
如果table2
中没有ID,则使用0
那个答案考虑(我最初认为那个)t2.Id可以重复 如果它是唯一的,请按
删除该组select
t1.id, t1.amount - isnull(t2.amount,0) as 'Totalamount'
from table1 T1
left join table2 T2
on t1.id = t2.id
order by t1.id