Skip to content
Advertisement

GBQ SQL: Using IF statement in a WHERE statement to filter data

Looking to filter data when multiple conditions are met. The table I have is below:

I need to keep rows that fulfill either one of the follow criteria:

  • If STOCK > 0 THEN KEEP ROW
  • If STOCK <= 0 AND TIME is within 2 weeks from today THEN KEEP ROW

The result table should look like this:

For my WHERE statement in my code I can do the first part of the criteria but am getting stuck at the second.

Not sure if the above code is right. Especially after the OR…

Advertisement

Answer

Your code looks basically correct. But it can be simplified to:

This makes two assumptions:

  • stock is not NULL.
  • time is not in the future.

These both seem reasonable.

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