ColumnA | CoumnB |
---|---|
1 | 5 |
2 | 1 |
3 | 10 |
4 | 8 |
1 | 4 |
1 | 5 |
2 | 5 |
In this,
- 1 is link with 5
- 5 is link with 2
- 2 is link with 1
- 1 is link with 4
- 4 is link with 8
- 1 is link with 5
- 5 is link with 2
So the output what I want is distinct values that are linked with each other
| output |
| ------------ |
| 1 |
| 5 |
| 2 |
| 4 |
| 8 |
3条答案
按热度按时间9vw9lbht1#
One approach that attempts to solve this problem is the following:
Each of these steps is done in a separate cte.
If you instead need to begin from a specific index and are looking for all linked nodes in the graph, you need a recursive query:
Then it's just sufficient to gather distinct values of ColumnB in the output. In the following case ColumnA = 1, if you want to change it, you need to change the value in the filtering condition of the base step
WHERE LEAST(ColumnA, ColumnB) = <your_value>
Output (for id = 1):
Check the demo here .
e5nszbig2#
I guess the following is what you are looking for, but I believe your sample data is not correct in respect of the desired output:
The idea is to unite the data in two groups and get only this records with count 2 - meaning we have x-y and y-x scenario.
The output of the above query is:
From there with another nested query or CTE you can get only the columns you want.
gj3fmq9x3#
Bsed on the simple data and the expected output, I think this is what you are looking for :
Result :
Demo here