Skip to content
Advertisement

SQL SERVER JOIN ID rows from one SELECT query to second SELECT query

Our fleet drivers accumulate hours in each type of rig that we operate.

This first query returns a list of driver IDs for a given route.

Result:

I need to feed these IDs into this second query, which returns the number of accumulated hours for a given Driver ID.

I’m trying to achieve:

EDIT: For clarification, if it helps, both queries join the ROSTER table to a different set of joined tables. The ID is in the ROSTER table in both queries. The first query selects the IDs, but the second query needs to use those IDs.

Both queries work fine independently of each other if I manually supply the specific ID I want for the second query.

I know how to do this with a cursor, but I know there must be some way to do this in a JOIN.

I tried several approaches:

And I tried various incarnation of:

But could never quite get the syntax to work.

I do not have access to modify the database in any way, so I cannot create VIEWs to do this.

This question is very similar to what I am trying to do, but it received no answer:

SQL Server – Join results of one query to first matching result from second query

Advertisement

Answer

You should be able to use an IN expression to use the results from the first query in the second. For example, using a CTE:

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