Need single query for this condition

Elaya Raja 96 Reputation points
2022-05-18T08:48:11.047+00:00

Id C1 C2


1 A A1


2 B B1


3 A A2


4 A A


5 B B3


6 B B4


If I give the ID value, I have to show the equaling C2 value
condition 1. if C2= C1 then I have to get all C2 values where C2=C1
eg. id= 4, out put is A, A1, A2
id = 5 , output is B3
id= 1, out put is A1
Thanks in Advance.

Azure Database for MySQL
Azure Database for MySQL
An Azure managed MySQL database service for app development and deployment.
710 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,551 questions
0 comments No comments
{count} votes

2 additional answers

Sort by: Most helpful
  1. Viorel 111.8K Reputation points
    2022-05-18T09:11:56.82+00:00

    Try a solution:

    declare @id int = 4
    
    select t1.C2
    from MyTable t1
    inner join MyTable t2 on t2.Id = t1.Id or (t2.C1 = t2.C2 and t2.C1 = t1.C1)
    where t2.Id = @Id
    
    1 person found this answer helpful.
    0 comments No comments

  2. Jingyang Li 5,891 Reputation points
    2022-05-18T13:21:23.703+00:00
    declare @id int=4
    create table test   (Id int, C1 varchar(2), C2 varchar(2))
    insert into test  values 
     (1,'A','A1')
    ,(2,'B','B1')
    ,(3,'A','A2')
    ,(4,'A','A')
    ,(5,'B','B3')
    ,(6,'B','A4')
     select * from test t1
     where t1.id=@id or 
     exists(select 1 from test t2 where  t2.id=@id  and t1.C1=t2.C2)
    
    
     drop table test
    
    0 comments No comments