A Simple SQL Query

chuck DM 101 Reputation points
2025-01-21T14:07:34.2966667+00:00

I have the following table:-

User's image

I want Col 1 and Col 2 where Col2 =1 and the corresponding all the values of Col 1 where Col 1 =2. But this is an example. I can find 1st part (i.e,, Select Col1, Col 2 from Table1 where Col 2 =1). But my problem is how do we know the value of Col 1 is 2 where Col 2 =1?

The result set would be :-

User's image

Any help please??

SQL Server SQL Server Transact-SQL
Developer technologies Transact-SQL
SQL Server Other
{count} votes

Accepted answer
  1. Yitzhak Khabinsky 26,586 Reputation points
    2025-01-21T14:57:38.7266667+00:00

    Hi @chuck DM,

    Please try the following solution leveraging EXISTS.

    -- DDL and sample data population, start
    DECLARE @tbl TABLE (col1 INT, col2 INT);
    INSERT INTO @tbl (col1, col2) VALUES
    (2, 1),
    (2, 3),
    (2, 5),
    (3, 4),
    (5, 6);
    -- DDL and sample data population, end
    
    SELECT * FROM @tbl AS a
    WHERE EXISTS (
    SELECT 1 FROM @tbl AS b
    WHERE b.col2 = 1
    	AND b.col1 = a.col1);
    
    0 comments No comments

0 additional answers

Sort by: Most helpful

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.