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除いて、null 値を取得します。table1.idtable2.id

null値を値にする必要があるため、null値があることを除いて、すべて問題ありませ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.00table1.id、結果セットにnullがあるのには実際の金額の値があります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の合計が取得table2joinれ、ID ごとに計算され、差が計算されます。に 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 に答える