2012-08-22 46 views
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 

結果是從表1的所有值 - amounttable2除了table1.id的不在table2.id的他們得到空值。SQL Server查詢獲得行表1 - 行表2無空值

所以,這只是我的空值都好,因爲我需要這些是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的是,在結果集爲空確實有table1.amount

概述我需要什麼

一個真正的量值210
table 1 values (1,12 ; 2,27 ; 3,9) table 2 values (1,9 ; 3,12) result table (1,3 ; 2,27 ; 3,-3) 

,所以我需要表1 - 從表2的值來獲得結果表

+0

這是刪除該組*金額*(用一個'm' - 不是* ammount *)... –

回答

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 

這將通過id來獲取每個ID的總Sumtable2 然後將join ,並做出區別。 如果在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 
+0

tanx m8我幾乎可以看到它的工作可以測試它tomorow。 – AntoonVs