向计算字段添加过滤器 SQL

Adding filters to calculated fields SQL

我有一个包含这些字段的 table:

RefDate
Symbol
Timestamp
Sequence
Quantity
Price
SaleCondition
Pid
SubMkt

它有一个股票交易列表,包括日期 (RefDate)、代码 (AAPL、MSFT、DAVE、AMZN)、数量、价格等。

SaleCondition 包含我需要用来查找各种内容的代码列表,例如"O"代表"opening trade","6"代表"closing trade",依此类推

我需要计算开盘价、收盘价、min/max/avg价格、VWAP(成交量加权平均价)、交易次数、交易股数和波动率(计算为最大价格-最低 Price/Last 价格)。

我必须排除 SaleCondition 中的许多代码才能获得 min/max/avg/VWAP,我做对了。

但是我不知道如何将开盘价和收盘价拉入查询。我基本上需要给出一个计算的字段条件(Select PRICE where SaleCondition="O" and PID="Q")。显然我不能那样做,因为我需要 WHERE 子句来排除许多其他代码。

这是我的想法。第一个生成正确的 min/max/average/vwap 但 opening/closing 价格是占位符,而 Shares/Trades 不正确。后两个查询是正确的开盘价和收盘价。

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'")

我认为您正在寻找条件聚合。您可以在聚合函数中实现逻辑,而不是排除 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