SQL:将两个to-from(方向)列交换为两个单向列

时间:2017-03-12 07:18:30

标签: sql postgresql graph-theory

我正在处理一些与图形相关的数据,这些数据具有定向到来自节点。这是最初的模拟数据。

enter image description here

但是,我试图将其分析为单向路径。这意味着我将以某种方式需要将node1的一些行与node2交换以进行分组。如下所示。

enter image description here

有谁知道如何为此编写SQL查询?谢谢!

以逗号分隔的模拟初始数据。

id,node1,node2,count
1,A,B,10
2,B,A,20
3,C,B,30
4,C,A,30
5,A,C,20
6,B,C,10

1 个答案:

答案 0 :(得分:1)

您显然希望较小的值为node1。这可以使用least()greatest()函数完成:

select id, 
       least(node1, node2) as node1, 
       greatest(node1, node2) as node2,
       "count"
from the_table;