Skip to content
Advertisement

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

I have an existing excel formula. The logic is this:

  1. Start looking when dates on Table 2 “Date/Time” are greater than Table 1 “Open_Date”
  2. Stop looking when dates on Table 2 “Date/Time” that are less than Table 1 “Close_Date”
  3. If Table 1 “Action” says “Buy”, then find where the Table 2 “Low” is less than Table 1 Column L “FixedSL”.
  4. If Table 1 “Action” says “Sell”, then find where the Table 2 “High” is less than Table 1 Column L “FixedSL”.
  5. If match is found, return the “Date/Time” in Table 2 and overwrite the value in Table 1 “Time_Hit_Fixed_SL” for that row.

Here are samples of the data tables: Table 1

Table 2

The forumula’s output for the Table 1’s first row would be 06/01/2020 03:57 overwriting the existing value in the “Time_Hit_Fixed_SL” column.

What I am looking to accomplish is to perform this same action in SQL with the data in 2 Tables.

I am new to SQL and searched, but couldn’t find the right direction to obtain the guidance of where to start with writing queries to replace advanced excel formula logic. I appreciate the help and guidance!

Advertisement

Answer

You can use window function MIN() to get the value of the column Date/Time.

If you want a SELECT statement that returns your expected result:

If you want to update Table1:

See the demo.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement