2

Sql - find the value of one column to find all other values ​​of another column

 2 years ago
source link: https://www.codesd.com/item/sql-find-the-value-of-one-column-to-find-all-other-values-of-another-column.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Sql - find the value of one column to find all other values ​​of another column

advertisements

This is a SQL question, I will try my best to explain.

I have a table like the following below

id  name    accounts
1   Jim 7001
1   Jim 7002
1   Jim 7003
2   Ryan    7001
3   Todd    7001
3   Todd    7003
2   Ryan    7002
4   Cam 7001
5   Fran    7001
2   Ryan    7003
1   Jim 7004

I am first trying to find all values with accounts column of '7001' to find the correct id's. After that I need to only pull the lines with those id's so I can see all the accounts for those specific ids.

example code I am using

select
s.id,
s.name,
s.account

from
students s

where
s.account in ('7001','7002','7003','7004')


I can do this with 2 queries one to find id's with '7001' account value and then run another query just for id's but would like to know if there is a way to write in order to have it all calculate in one shot.

Thanks in advance!


SELECT  *
FROM    tableName
WHERE   ID IN
        (
            SELECT ID
            FROM   tableName
            WHERE  accounts = 7001
        )

The JOIN version (recommended)

SELECT  a.*
FROM    students a
        INNER JOIN students b
          ON a.ID = b.ID
WHERE   b.accounts = 7001


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK