代码之家  ›  专栏  ›  技术社区  ›  jodu

Postgres-单个大表上的数据操作

  •  0
  • jodu  · 技术社区  · 7 年前

    我有下面的postgres表,其中有大约 .

    id |基础|选项|符号|选项|类型|到期|日期|罢工|中间|

    我需要在几秒钟内执行以下操作:

    1. 获取选项为foo和expiration\u date的所有行>2017-12-01
    2. 使用option_type=bar和expiration\u date>获取所有行;2017-12-01
    3. 对于查询#1的每一行,循环查询#2的结果行,使用相同的基础和到期日,并计算从strike#1和strike#2的值得出的价差。

    如何执行以下示例中的“查询中”计算(spread\u profit、spread\u distance、spread\u max\u loss、spread\u profit\u ratio)?

    SELECT a.underlying, 
           a.expiration_date, 
           (a.strike - b.strike) as spread_profit, 
           (a.mid - b.mid) as spread_distance, 
           (spread_distance - spread_profit) as spread_max_loss,
           (spread_profit / spread_max_loss) as spread_profit_ratio 
    FROM option_data a
       JOIN option_data b ON a.underlying = b.underlying AND a.expiration_date = b.expiration_date
    WHERE a.option_type = 'foo' 
      AND b.option_type = 'bar' 
      AND a.expiration_date <= '2017-12-01' 
      AND b.expiration_date <= '2017-12-01' 
    GROUP BY a.underlying, a.expiration_date 
    ORDER BY spread_profit_ratio DESC
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Chris Curvey    7 年前

    我不是百分之百确定你想做什么,但答案可能是这样的:

    select a.underlying
    , a.expiration_date
    , max(a.strike - b.strike) as spread
    from mytable a
    join mytable b on a.underlying = b.underlying 
              and a.expiration_date = b.expiration_date
    where a.option_type = 'foo' 
    and b.option_type = 'bar'
    group by a.underlying, a.expiration_date