我有一个包含以下字段的表格:
RefDate
Symbol
Timestamp
Sequence
Quantity
Price
SaleCondition
Pid
SubMkt
它具有带有日期(RefDate),交易品种(AAPL,MSFT,DAVE,AMZN),数量,价格等的股票交易列表。
SaleCondition
包含一个代码列表,我需要使用这些代码来查找各种内容,例如"O"
代表“开放贸易”,"6"
代表“封闭贸易”,依此类推。
我需要计算开盘价,收盘价,最小/最大/平均价格,VWAP(交易量加权平均价格),交易数量,交易的股票数量和波动率(计算为最高价格-最低价格/最低价格。
我必须排除SaleCondition
中的许多代码才能获得min / max / avg / VWAP,这是我正确完成的。
但是我不知道如何将开盘价和收盘价拉入查询。我基本上需要给出一个计算得出的字段条件(Select PRICE where SaleCondition="O" and PID="Q"
)。显然,我不能这样做,因为我需要WHERE
子句来排除许多其他代码。
这就是我想出的。第一个产生正确的最小/最大/平均/ vwap,但开盘/收盘价是占位符,而股份/交易不正确。后两个查询是正确的开盘价和收盘价。
dbGetQuery(nqdb, statement =
"select
RefDate,
Symbol,
Price as OpeningPrice,
Price as ClosingPrice,
Min(Price) as MinPrice,
Max(Price) as MaxPrice,
AVG(Price) as AvgPrice,
Sum(Quantity*Price)/Sum(Quantity) as VWAP,
Count(Quantity) as Trades,
Sum(Quantity) as Shares,
(Max(Price)-Min(Price))/(Price) as PctRange
from trds
where
SaleCondition not like '%C%' and
SaleCondition not like '%G%' and
SaleCondition not like '%I%' and SaleCondition not like '%H%' and
SaleCondition not like '%M%' and SaleCondition not like '%N%' and
SaleCondition not like '%P%' and SaleCondition not like '%Q%' and
SaleCondition not like '%R%' and SaleCondition not like '%T%' and
SaleCondition not like '%U%' and SaleCondition not like '%V%' and
SaleCondition not like '%W%' and SaleCondition not like '%Z%' and
SaleCondition not like '%4%' and SaleCondition not like '%7%' and
SaleCondition not like '%9%'
group by Symbol order by PctRange DESC")
dbGetQuery(nqdb, statement =
"select
RefDate,
Symbol,
Price as OpeningPrice
from trds
where SaleCondition like '%O%' and Pid='Q'")
dbGetQuery(nqdb, statement =
"select
RefDate,
Symbol,
Price as ClosingPrice
from trds
where SaleCondition like '%6%' and Pid='Q'")
答案 0 :(得分:0)
我认为您正在寻找条件聚合。您可以在聚合函数中实现逻辑,而不是排除WHERE
子句中的记录。由于您不排除记录,因此您可以访问进行所有计算所需的所有数据。
以下是根据您的原始查询开盘价和收盘价的示例。您可以根据需要在其他计算中添加任意多的列。
SELECT
RefDate,
Symbol,
MAX(CASE WHEN SaleCondition LIKE '%O%' AND Pid='Q' THEN Price END) as OpeningPrice,
MAX(CASE WHEN SaleCondition LIKE '%6%' AND Pid='Q' THEN Price END) as ClosingPrice
FROM trds
GROUP BY
RefDate,
Symbol