Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何使用两列进行分组,反之亦然_Sql_Postgresql - Fatal编程技术网

Sql 如何使用两列进行分组,反之亦然

Sql 如何使用两列进行分组,反之亦然,sql,postgresql,Sql,Postgresql,我有这种桌子 a_id | b_id 1 | 2 2 | 1 2 | 1 1 | 2 3 | 1 1 | 4 如果它的1我想得到a_id=1或b_id=1类似的不同组合 result 2 3 4 它类似于具有两列的group by,但在每对列中使用相同的值(反之亦然)。有什么可能的方法来处理这个问题吗?您可以使用union: select b_id as result from t where a_id

我有这种桌子

a_id | b_id
   1 |    2
   2 |    1
   2 |    1
   1 |    2
   3 |    1
   1 |    4
如果它的
1
我想得到
a_id=1
b_id=1
类似的不同组合

result
   2
   3
   4

它类似于具有两列的group by,但在每对列中使用相同的值(反之亦然)。有什么可能的方法来处理这个问题吗?

您可以使用
union

select b_id as result from t where a_id = 1 union
select a_id from t where b_id = 1;
还有其他方法。比如,横向托梁:

select distinct x.result
from t, lateral
      (values (case when a_id = 1 then b_id else a_id end) x(result)
where 1 in (a_id, b_id);
或者更直接地查询:

select distinct x(case when a_id = 1 then b_id else a_id end) as result
from t
where 1 in (a_id, b_id);

因为要删除重复项,
distinct
将主导几乎所有方法的性能。

如果每行都有一个已创建的位置,我希望结果按已创建的位置排序,那么结果应该是
4,3,2
。有办法吗?@CarlosGarcia。你应该把新问题作为一个问题而不是在评论中提出。