0

I have a table with columns Date, UserID, EventID, Value, RangeOfValues.

The task is two determine a pair of values from the last columns between which is the value from the 4th columns. So, for example, if the user on the screenshot has value 326 in Value clmn it will be between 200 and 1000. I have a lot of users and need to extract such pairs for each of them. Can do this in python but have no ideas how to do this in bigquery (or even if it's possible).

Any advice would be appreciated! enter image description here

The table looks like this

1 Answer 1

2

Yes, this is easily achievable using UNNEST() to turn the array into rows and then run simple sub-queries on them:

WITH test as (
  SELECT * FROM UNNEST([
    STRUCT(4 as value, [1, 3, 5, 7, 9, 100, 150, 40] as rangeOfValues)
    ,(15, [1, 3, 5, 7, 9, 100, 150, 40])
    ,(50, [1, 3, 5, 7, 9, 100, 150, 40])
    ,(160, [1, 3, 5, 7, 9, 100, 150, 40])
  ])
)

SELECT  
  value,
  (SELECT MAX(r) FROM UNNEST(rangeOfValues) r WHERE r<value ) nextLowest,
  (SELECT MIN(r) FROM UNNEST(rangeOfValues) r WHERE r>value ) nextBiggest
FROM test
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.