获取按另一列分组的列的总和,然后将其分组到另一列

时间:2012-06-26 14:46:56

标签: sql sql-server sql-server-2008 tsql sql-server-2008-r2

我已经尝试了一段时间来解决这个问题,但是我缺乏更高级的SQL技能阻碍了我。

Executions(TradeDate, Symbol, Side, Price, Under, Account)

TEMP DATA:
2012-06-20, AAPL 120716C00600000, BUY, 3.25, AAPL, XYZ123
2012-06-20, AAPL 120716C00600000, SELL, 3.30, AAPL, XYZ123
2012-06-20, AAPL 120716C00600000, BUY, 3.25, AAPL, XYZ123
2012-06-20, AAPL 120716C00600000, SELL, 3.30, AAPL, XYZ123
2012-06-20, GRPN 120716C00027000, BUY, 2.25, GRPN, XYZ123
2012-06-20, GRPN 120716C00027000, SELL, 2.30, GRPN, XYZ123
2012-06-20, GRPN 120716C00027000, SELL, 2.30, GRPN, XYZ123
2012-06-20, GRPN 120716C00027000, BUY, 2.25, GRPN, XYZ123


-UNDER----Side(Buy)----Side(Sell)
 AAPL      6.50         6.60
 GRPN      4.50         4.60

正如你所看到的那样,我正试图获得每一方价格的总和,然后按下划分。

4 个答案:

答案 0 :(得分:6)

使用GROUP BY分组Under列和与CASE相关联的SUM来获取所需结果:

SELECT e.Under,
       SUM(case when e.Side = 'BUY' them e.Price else 0 end) as 'Side(Buy)',
       SUM(case when e.Side = 'SELL' them e.Price else 0 end) as 'Side(Sell)'
FROM Executions e
GROUP BY e.Under

答案 1 :(得分:3)

您可以使用PIVOT。 (见SQL Fiddle for Demo

select *
from 
(
    select under, price, side
    from executions
) x
PIVOT
(
    sum(price)
    for side in ([BUY], [SELL])
) p

答案 2 :(得分:0)

这是一种方法:

SELECT e.under
     , SUM(CASE WHEN e.side = 'BUY'  THEN e.price ELSE NULL END) AS [Side(Buy)]
     , SUM(CASE WHEN e.side = 'SELL' THEN e.price ELSE NULL END) AS [Side(Sell)]
  FROM Executions e
 GROUP BY e.under

这里的“技巧”是使用CASE表达式仅返回某些边值的Price。 (注意:有人会不可避免地指出,ELSE NULL是隐式的,可以省略。)

这不是唯一的方法。但是,如果您还需要获得每个总和中包含的行的“计数”以及所有行的计数,那么这是一种非常灵活的方法。为了说明这种方法的实施:

 SELECT e.under
     , SUM(CASE WHEN e.side = 'BUY'  THEN e.price ELSE NULL END) AS [SUM_Side(Buy)]
     , SUM(CASE WHEN e.side = 'BUY'  THEN 1       ELSE 0    END) AS [COUNT_Side(Buy)]
     , SUM(CASE WHEN e.side = 'SELL' THEN e.price ELSE NULL END) AS [SUM_Side(Sell)]
     , SUM(CASE WHEN e.side = 'SELL' THEN 1       ELSE 0    END) AS [COUNT_Side(Sell)]
     , SUM(CASE WHEN e.side IN ('BUY','SELL') THEN 1 ELSE 0 END) AS [COUNT_(Buy+Sell)]
  FROM Executions e
 GROUP BY e.under

这种方法通常具有非常可预测的性能,并且它要求仅对源数据集引用一次(在本例中为简单的表引用)

这种方法几乎适用于所有关系数据库。 (Oracle,SQL Server,MySQL,Teradata,DB2,...)

答案 3 :(得分:0)

 select Symbol, sum(case when side = 'BUY' THEN Price else 0 END) as [Side(Buy)], sum(case when side = 'SELL' THEN Price else 0 END) as [Side(Sell)] group by Symbol