How to write a Simple TSQL

chuck DM 101 Reputation points
2025-01-21T14:52:01.98+00:00

I have the following table:-

User's image

I have two requirements. the 1st one is, I need ColA and ColB when ColB is 1. So the query would be:-

Select ColA, ColB from Table1 where ColB =1.

The Output of the 1st requirement is:-

User's image

Now the 2nd requirement is, as the value of ColA is 2 when ColB =1, So I need ColA and ColB when ColA is 2. But the problem is that I don't know the value of ColA when ColB is 2. I simply can't write

Select ColA, ColB from Table1 where ColA =2.

The final output would be

User's image

SQL Server Transact-SQL
SQL Server Transact-SQL
SQL Server: A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.Transact-SQL: A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
114 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,685 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 119.2K Reputation points
    2025-01-21T14:54:33.8966667+00:00

    Try this query:

    select t2.*
    from Table1 t1 
    inner join Table1 t2 on t2.ColA = t1.ColB
    where t1.ColB = 1
    
    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.