ttist25
asked on
SQL - Use results of SELECT DISTINCT in a JOIN
Hey there!
I'm working in MSSQL 2012 and I'm trying to make a little script that will get the distinct values in table1.field1 and pull the records from table2 where table2.field1 matches any of the distinct table1.field1 values.
So - let's say I run this:
SELECT DISTINCT field1 FROM Table1 WHERE Table1Key='MyKey'
and get these results:
field1
--------
1
--------
2
--------
3
--------
The script would essentially do this:
SELECT * FROM Table2 WHERE field1 in ('1', '2', '3')
Any ideas how I can do this?
TIA!
I'm working in MSSQL 2012 and I'm trying to make a little script that will get the distinct values in table1.field1 and pull the records from table2 where table2.field1 matches any of the distinct table1.field1 values.
So - let's say I run this:
SELECT DISTINCT field1 FROM Table1 WHERE Table1Key='MyKey'
and get these results:
field1
--------
1
--------
2
--------
3
--------
The script would essentially do this:
SELECT * FROM Table2 WHERE field1 in ('1', '2', '3')
Any ideas how I can do this?
TIA!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Though the DISTINCT shouldn't be needed, right?
ASKER
Awesome! Thanks guys.
I ended up using IN because I had to modify the values in the distinct with 'blah' + (replace.. and in my head IN seemed to make more sense for that.
THANKS AGAIN! :D
I ended up using IN because I had to modify the values in the distinct with 'blah' + (replace.. and in my head IN seemed to make more sense for that.
THANKS AGAIN! :D