any help greatly appreciated. Quite stumped on this one! Amateur at SQL, but think BigQuery isn't helping me out here.
I have a table that looks something like this:
Object ID1 ID2
A 1 null
B 2 1
C 3 2
D 4 3
A, B, C and D are actually the same object. You can see that they are linked by a "chain" of child IDs. A is the "master" object.
I would like a new column in this table which returns "A" (or equivalent) for linked objects (calling this P1-Obj). Here's what I'd like the output to look like:
P1-Obj Object ID1 ID2
A A 1 null
A B 2 1
A C 3 2
A D 4 3
E E 5 null
E F 6 5
E G 7 6
E H 8 7
This would have to work with "chains" of arbitrary length (i.e. could have 0-100 objects connected to P1-Obj).
I solved this in a spreadsheet using this formula - imagining that the above table had columns A-D, this formula works when put in column A: =IF(ISBLANK($D2),$B2,INDIRECT("A"&MATCH($D2,$C:$C,0))). I need the SQL equivalent of this!
So far, I tried to use a CTE with recursion to get me started on a data structure I could then work with to get to the above.
Something like:
WITH cte as (
SELECT *
FROM table
where ID2 is null
UNION ALL
SELECT m.*
FROM table m
JOIN cte o
on m.ID1 = o.ID2)
select *
from cte
But BigQuery spits back out: "Table name "table" missing dataset while no default dataset is set in the request" - and from a quick google it looks recursive CTE's are not supported on BigQuery.
I'm not even sure if a recursive CTE is the right thing that I'm looking for to start solving my problem, but I haven't been able to even get an output to see - and every other google avenue has taken me to a dead end.
I'm pretty stumped here as to if there's another way to do this in BigQuery (or with SQL in general)!
Thanks so much in advance for any advice.
EDIT: Added fiddle: https://www.db-fiddle.com/f/m6EN38upDhFLt7eUwtKrLa/3
Not sure if that's doing what I need it to...