SQL 查询 - 如何将此 excel 公式转换为查询

SQL Query - how to translate this excel formula into a query

我有一个现有的 excel 公式。逻辑是这样的:

  1. 当 Table 2 "Date/Time" 大于 Table 1 "Open_Date"
  2. 时开始查找
  3. 当 Table 2 "Date/Time" 上的日期小于 Table 1 "Close_Date"
  4. 时停止查找
  5. 如果 Table 1“行动”显示“买入”,则找到 Table 2 “低”小于 Table 1 L 列“固定止损”的位置。
  6. 如果 Table 1 "Action" 说 "Sell",然后找到 Table 2 "High" 小于 Table 1 L 列 "FixedSL" 的位置。
  7. 如果找到匹配项,return Table 2 中的“Date/Time”并覆盖 Table 1 中的值“Time_Hit_Fixed_SL”行。

以下是数据表的示例: Table 1

Open_Date,       Close_Date,   Action, FixedSL,  Time_Hit_Fixed_SL
6/1/2020 3:56,  6/1/2020 4:24,  Buy,   1.8502,   6/1/2020 5:01
6/1/2020 4:44,  6/1/2020 8:19,  Sell,  1.8411,   6/1/2020 10:12
6/1/2020 8:22,  6/1/2020 8:54,  Sell,  1.8335,   6/1/2020 10:12

Table 2

Date/Time,        Open,     High,     Low,    Close
06/01/2020 03:57,  1.8503,  1.8503,  1.8501,  1.8501
06/01/2020 03:58,  1.8501,  1.8503,  1.8501,  1.8502
06/01/2020 03:59,  1.8501,  1.8504,  1.8501,  1.8504
06/01/2020 04:00,  1.8501,  1.8505,  1.8501,  1.8503
06/01/2020 04:01,  1.8504,  1.8504,  1.8504,  1.8504

Table 1 第一行的论坛输出将是 06/01/2020 03:57 覆盖“Time_Hit_Fixed_SL”列中的现有值。

我想要完成的是在 SQL 中使用 2 Table 秒中的数据执行相同的操作。

我是 SQL 的新手并进行了搜索,但找不到正确的方向来获取从何处开始编写查询以替换高级 excel 公式逻辑的指导。感谢您的帮助和指导!

您可以使用如下更新语句:

update table1 t1
set t1.Time_Hit_Fixed_SL 
    = coalesce(select min(t2.date_time) 
                 from table2 t2
                where t2.date_time between t1.start_date and t2.end_Date
                  and (t1.action = 'Buy' and t2.high < t1.fixed_SL)
                       OR (t1.action = 'Sell' and t2.low < t1.fixed_SL))
                )
               ,t1.Time_Hit_Fixed_SL);

您可以使用 window 函数 MIN() 来获取列 Date/Time 的值。

如果您想要 SELECT 声明 returns 您的预期结果:

SELECT DISTINCT t1.Open_Date, t1.Close_Date, t1.Action,  
  COALESCE(
    MIN(
      CASE t1.Action
        WHEN 'Buy' THEN CASE WHEN t2.Low < t1.FixedSL THEN t2.Date_Time END
        WHEN 'Sell' THEN CASE WHEN t2.High < t1.FixedSL THEN t2.Date_Time END
      END
    )
    OVER (PARTITION BY t1.Open_Date, t1.Close_Date),
    t1.Time_Hit_Fixed_SL
  ) Time_Hit_Fixed_SL
FROM Table1 t1 LEFT JOIN Table2 t2
ON t2.Date_Time > t1.Open_Date AND t2.Date_Time < t1.Close_Date

如果要更新Table1:

UPDATE Table1 AS t1
SET Time_Hit_Fixed_SL = COALESCE(
  (
    SELECT 
      MIN(
        CASE t1.Action
          WHEN 'Buy' THEN CASE WHEN t2.Low < t1.FixedSL THEN t2.Date_Time END
          WHEN 'Sell' THEN CASE WHEN t2.High < t1.FixedSL THEN t2.Date_Time END
        END
      )
    FROM Table2 t2  
    WHERE t2.Date_Time > t1.Open_Date AND t2.Date_Time < t1.Close_Date
  ),
  t1.Time_Hit_Fixed_SL
)

参见demo