SQL查询 - 如何获得行的多个单元格之和的差异

时间:2014-09-20 20:25:14

标签: mysql 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

基本上我在这里尝试获得独特账户的总购买价值。库存组合并减去总销售价值

这里的任何帮助都将受到高度赞赏。

提前致谢

3 个答案:

答案 0 :(得分: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子句。

答案 1 :(得分: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

答案 2 :(得分: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