简体   繁体   English

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

[英]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, 上面是我的示例数据,我希望我的SQL查询结果像这样,

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 小提琴测试: 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. 我根据您的评论添加了HAVING子句。

Just to reduce duplication I would change Brian's code to this: 为了减少重复,我将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
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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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