简体   繁体   中英

SQL Query - How to get difference of sum of multiple of cells of rows

I need to get the difference of the sums of two fields which are in single table (really sorry if this is confusing), please read on for an example

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

Above is my sample data and I would my SQL query result to be something like,

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

basically here I am trying to get the total buy value of unique account & stock combination and subtract with the total sell value

Any help here would be highly appreciated.

Thanks in advance

Fiddle Test: 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

I added the HAVING clause based on your comment.

Just to reduce duplication I would change Brian's code to this:

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
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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM