0
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除了table2不在'stable1.id中的table2.id's 他们得到空值。

所以这一切都很好,除了我有空值,因为我需要这些作为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结果集中有 null 的 's 确实有一个真实的金额值table1.amount

我需要的概述

table 1   values    (1,12 ; 2,27 ; 3,9) table 2   values    (1,9 ; 3,12) result table (1,3 ; 2,27 ; 3,-3)

所以我需要 table1 - 表 2 中的值来获取结果表

4

1 回答 1

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 然后将按joinid 计算,并做差值。如果没有 id table2,将使用 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
于 2012-08-22T17:15:28.803 回答