4

我已经尝试了一段时间来解决这个问题,但是我缺乏更高级的 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

4 回答 4

6

用于GROUP BYUnder列分组并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
于 2012-06-26T14:51:19.817 回答
3

您可以为此使用PIVOT 。(参见SQL Fiddle 的演示

select *
from 
(
    select under, price, side
    from executions
) x
PIVOT
(
    sum(price)
    for side in ([BUY], [SELL])
) p
于 2012-06-26T14:53:24.617 回答
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 表达式仅返回特定侧值的价格。(注意:正如有人不可避免地指出的那样,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

这种方法通常具有非常可预测的性能,并且它要求源数据集只被引用一次(在这种情况下,一个简单的表引用)

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

于 2012-06-26T14:52:10.720 回答
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
于 2012-06-26T14:52:14.907 回答