1

I'm trying to do select from Table2 for each row in an initial select statement from Table1.

Initial select statement would look something like

Select * from Table1 Where GroupID='someId' AND ObjectID='someID'

Table1 would return something like the following (there will only ever be 0-1 returned rows with a null EndDate value).

enter image description here

Table2 will look as follows

enter image description here

Basically my goal is to loop through the first select statements rows. For each row I want to take the objectid, startdate, and enddate to select all the appropriate rows in Table2. Then after do a UNION(?) on all the data I've selected from Table2. I want to be able to select all the rows in Table2 which's objectid matches the objectid given and the timestamp is in-between the start/end dates (or to current timestamp if enddate is null). Does that make sense? I've been looking online, but have not found a way to achieve a looping select union like this.

I'm not sure if this is possible in a single select statement or if a stored proc is needed/cleaner (either is fine but I'd rather avoid stored proc if I can).

0

1 Answer 1

1

You can do it with a join:

SELECT t2.*
FROM Table2 t2 INNER JOIN Table1 t1
ON t1.objectid = t2.objectid 
AND t2.timestamp BETWEEN t1.startdate AND COALESCE(t1.enddate, current_timestamp)
WHERE t1.GroupID = 'someId' AND t1.ObjectID = 'someID'
Sign up to request clarification or add additional context in comments.

1 Comment

This works beautifully, thank you! Wasn't aware of the COALESCE function so thank you for that as well.

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.