2014-09-20 26 views
0

我需要獲得單個表格中兩個字段的總和的差異(真的很抱歉,如果這是令人困惑),請閱讀例子SQL查詢 - 如何獲得行的單元格的倍數總和的差異

 
Id type account_id stock_id volume price value 
========================================================== 
1 BUY  1   1    5  500  2500 
2 BUY  1   4   30  200  6000 
6 BUY  1   1   10  500  5000 
7 SELL  1   1    3  500  1500 
8 SELL  1   1    2  500  1000 
9 SELL  1   4   20  120  2400 

以上就是我的樣本數據,我將我的SQL查詢結果是這樣的,

 
account_id stock_id volume totalAmount 
============================================ 
1   1   10  5000 
1   4   10  3600 

基本上在這裏,我想獲得的唯一帳戶&股票組合的總購買價值減去總銷售價值爲

任何幫助在這裏將不勝感激。

在此先感謝

+0

你有沒有嘗試過的東西,以獲得預期的結果? – 2014-09-20 20:26:53

回答

4

小提琴測試: http://sqlfiddle.com/#!2/53035/1/0

select account_id, 
     stock_id, 
     sum(case when type = 'BUY' then volume else -volume end) as volume, 
     sum(case when type = 'BUY' then value else -value end) as totalamount 
from  tbl 
group by account_id, 
     stock_id 
having sum(case when type = 'BUY' then volume else -volume end) <> 0 

我增加了一個基於您的評論HAVING子句。

+0

正是我想要的......太快了。非常感謝:) – abdulH 2014-09-20 20:40:40

+0

如何避免結果總和(如果type ='BUY'then volume else -volume end)的結果爲ZERO? – abdulH 2014-09-20 21:36:50

+0

@aaha使用having子句,請參閱編輯答案 – 2014-09-20 21:38:14

0

只是爲了減少重複我會改變Brian的代碼如下:

SELECT 
    account_id, 
    stock_id, 
    SUM(volume * type_sign) as total_volume, 
    SUM(value * type_sign) as total_value 
FROM 
    (select t.*, case when type = 'BUY' then 1 else -1 end as type_sign 
    from tbl) t 
GROUP BY account_id, 
     stock_id 
0
select buy.account_id,buy.stock_id,(buy.volume-sell.volume) volume,(buy.totalAmount-sell.totalAmount) totalAmount from 
(select account_id,stock_id,sum(volume) volume,sum(value) totalAmount from stock 
where type = 'BUY' 
group by account_id,stock_id) buy 
inner join 
(select account_id,stock_id,sum(volume) volume,sum(value) totalAmount from stock 
where type = 'SELL' 
group by account_id,stock_id) sell 
on buy.account_id = sell.account_id and buy.stock_id = sell.stock_id 
相關問題