Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/database/9.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
PostgreSQL-使用SQL模拟循环和聚合_Sql_Database_Postgresql - Fatal编程技术网

PostgreSQL-使用SQL模拟循环和聚合

PostgreSQL-使用SQL模拟循环和聚合,sql,database,postgresql,Sql,Database,Postgresql,我有一个类似于此的SQL表 ID | COL1 | COL2 | SIM ======================================= 1 | A | B | 5 2 | Z | A | 3 3 | C | B | 3.5 4 | B | Z | 0.5 5 | C |

我有一个类似于此的SQL表

ID  |   COL1    |   COL2    |   SIM
=======================================
1   |   A       |   B       |   5
2   |   Z       |   A       |   3
3   |   C       |   B       |   3.5
4   |   B       |   Z       |   0.5
5   |   C       |   Z       |   1.1
我正在尝试创建一个查询,对于
COL1
COL2
中的每个唯一值,将聚合相应
COL
列中的值以及
SIM
值。 期望输出:

ID  |   AGG_KEY     |   AGG_IDS     |   AGG_SIM
========================================================
1   |   A           |   [B, Z]      |   [5, 3]
2   |   B           |   [A, C, Z]   |   [5, 3.5, 0.5]
3   |   C           |   [B, Z]      |   [3.5, 1.1]
4   |   Z           |   [A, B, C]   |   [3, 0.5, 1.1]

嗯。如果我理解正确,您可以“取消PIVOT”并聚合:

select v.cola, array_agg(v.colb order by t.sim desc), array_agg(t.sim order by t.sim desc)
from t cross join lateral
     (values (col1, col2), (col2, col1)) v(cola, colb)
group by v.cola;
他是一把小提琴