Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.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 挤压列为空的行_Postgresql - Fatal编程技术网

Postgresql 挤压列为空的行

Postgresql 挤压列为空的行,postgresql,Postgresql,我有一个表(在PostgreSQL数据库中),其中一些id的多行具有一些值,而一些为空。 该表如下所示(玩具示例): 最重要的是:我可以保证同一个id中没有行具有非空值。 在上面的示例中,id 1没有任何其他行 我希望聚合每个id的所有值,挤压非空值。就是把它变成这样的东西 id | x | y | z ----+-----+-----+---- 1 | 100 | 200 | 42 2 | 45 | | (2 rows) 我得到的最接近的方法是使用

我有一个表(在PostgreSQL数据库中),其中一些id的多行具有一些值,而一些为空。 该表如下所示(玩具示例):

最重要的是:我可以保证同一个id中没有行具有非空值。 在上面的示例中,id 1没有任何其他行

我希望聚合每个id的所有值,挤压非空值。就是把它变成这样的东西

 id |  x  |  y  | z  
----+-----+-----+----
  1 | 100 | 200 | 42  
  2 |  45 |     |    
(2 rows)
我得到的最接近的方法是使用级联的
COALESCE(field1)、| | COALESCE(field2)、| |……
,但结果不是我想要的:

PSQL:test/me@[local]=> SELECT id, COALESCE(x::TEXT || ',' , '') || COALESCE(y::TEXT || ',', '') || COALESCE(z::TEXT || ',', '') AS agg FROM t1 GROUP BY id, agg;
 id |   agg   
----+---------
  1 | 100,42,
  1 | 200,
  2 | 45,    
(3 rows)

知道如何解决这个问题吗?

只需使用聚合,例如
min()
-它将忽略空值:

select id, 
       min(x) as x, 
       min(y) as y, 
       min(z) as z
from t1
group by id;
这依赖于您的声明“我可以保证同一id中没有行具有非空值”,否则这当然会返回错误的信息


或者,您可以使用
array\u agg()
将所有值放入一个数组中,以防每个id可能有多个值。但是
string\u agg()
不会忽略空值,因此您需要为此应用筛选器:

select id, 
       array_agg(x) filter (where x is not null), 
       array_agg(y) filter (where y is not null),
       array_agg(z) filter (where z is not null)
from t1
group by id;

只需使用聚合,例如
min()
-它将忽略空值:

select id, 
       min(x) as x, 
       min(y) as y, 
       min(z) as z
from t1
group by id;
这依赖于您的声明“我可以保证同一id中没有行具有非空值”,否则这当然会返回错误的信息


或者,您可以使用
array\u agg()
将所有值放入一个数组中,以防每个id可能有多个值。但是
string\u agg()
不会忽略空值,因此您需要为此应用筛选器:

select id, 
       array_agg(x) filter (where x is not null), 
       array_agg(y) filter (where y is not null),
       array_agg(z) filter (where z is not null)
from t1
group by id;

感谢您提供依赖于我的声明的“min”解决方案和通用解决方案。两者都创造奇迹!感谢您提供依赖于我的声明的“min”解决方案和通用解决方案。两者都创造奇迹!