-1

I have table

a | b 
----- 
1 | 3 
3 | 2 
3 | 4 
2 | 5 
3 | 6 
2 | 7

how to write sql query if a = 1 then result 3 2 4 5 6 7, if a = 3 then 2 4 5 6 7, if 2 then 5 7 here is my query

select * 
from table
where a in (select b from table where a = 1) or a = 1

but the result only 3 2 4 6 because 3 has 2 in col b so i want also to have 5 7 thanks

GMB
  • 216,147
  • 25
  • 84
  • 135
Tôm Leè
  • 7
  • 6
  • Could you maybe explain the relationship between `a` and `b`? It's not immediately clear how the results are derived from the conditions that you've provided as examples – Jon Warren Mar 04 '20 at 21:21
  • Please tag your question with the database that you are using. – GMB Mar 04 '20 at 21:22
  • sorry for bad english. for example col a = 1 then col b = 3. i would like to get all values in col b which equal 3 result will be 2 4 6 and then again get all values in col b which equal 2 4 6 and so on. thanks – Tôm Leè Mar 04 '20 at 21:33

1 Answers1

0

I suspect that you have a hierarchical structure, where a is the parent and b is the child, and that you are looking for all descendents of a given node.

One common way to walk such structure is a hierarchical query. In SQL Server:

with cte as (
    select a, b from mytable where a = @your_parameter
    union all
    select t.a, t.b from mytable t inner join cte c on t.a = c.b 
)
select * from cte

Demo on DB Fiddle - when given 3 as parameter:

 a |  b
-: | -:
 3 |  2
 3 |  4
 3 |  6
 2 |  5
 2 |  7
GMB
  • 216,147
  • 25
  • 84
  • 135
  • hi. sorry. im using sql server. i tried your code but give me an error. Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'cte'. Completion time: 2020-03-05T04:37:14.0923830+07:00 – Tôm Leè Mar 04 '20 at 21:38
  • @TômLeè: ok so you are using SQL Server. Just remove the `recursive` keyword from the query, and it will work as intended. I edited my answer as well. – GMB Mar 04 '20 at 21:43
  • wow. great. it works. Thanks GMB, i have 1 more question. how can i make it in 1 line, example -> a = 1 then col a: 1 , col b: 3 2 4 5 6 7 (space or comma) Thanks so much – Tôm Leè Mar 04 '20 at 21:51
  • 1
    SQL Server 2016 and above, You can use string_agg to bring it into one row: https://learn.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-ver15 – CR7SMS Mar 04 '20 at 21:53
  • Thanks @CR7SMS, I will have a look at it – Tôm Leè Mar 04 '20 at 22:11