相关疑难解决方法(0)

Postgres - 以 JSON 数组或数组的形式返回行数据

在 PG v9.4 及更高版本上,我想将一些数据(基于 SELECT 语句)导出为JSON 数组

标准 json_agg 返回我想要的内容,但它返回对象数组(其中对象键是列名称)例如此查询:

SELECT json_agg(data_rows)
FROM (
        -- in memory table sample
    SELECT * FROM 
    (VALUES
        ('John',now(),1940,'Winston','Lennon'),
        ('Paul',now(),1942,'','McCartney'),
        ('George',now(),1943,NULL,'Harrison'),
        ('Ringo',now(),1940,'my passions are ring,drum and shades','Starr')
    ) AS x("FirstName", "CurrentDt", "BirthYear", "MiddleName", "LastName")
        ORDER BY "BirthYear" DESC, "FirstName" DESC
) AS data_rows
Run Code Online (Sandbox Code Playgroud)

返回以下内容:

[
 {"FirstName":"George","CurrentDt":"2016-09-12T13:13:07.862485-04:00","BirthYear":1943,"MiddleName":null,"LastName":"Harrison"}, 
 {"FirstName":"Paul","CurrentDt":"2016-09-12T13:13:07.862485-04:00","BirthYear":1942,"MiddleName":"","LastName":"McCartney"}, 
 {"FirstName":"Ringo","CurrentDt":"2016-09-12T13:13:07.862485-04:00","BirthYear":1940,"MiddleName":"my passions are ring,drum and shades","LastName":"Starr"}, 
 {"FirstName":"John","CurrentDt":"2016-09-12T13:13:07.862485-04:00","BirthYear":1940,"MiddleName":"Winston","LastName":"Lennon"}
]
Run Code Online (Sandbox Code Playgroud)

但我想要的是:

[
 ["George","2016-09-12T13:13:07.862485-04:00",1943,null,"Harrison"}, 
 ["Paul","2016-09-12T13:13:07.862485-04:00",1942,"","McCartney"}, 
 ["Ringo","2016-09-12T13:13:07.862485-04:00",1940,"my passions are ring,drum and shades","Starr"}, 
 ["John","2016-09-12T13:13:07.862485-04:00",1940,"Winston","Lennon"}
]
Run Code Online (Sandbox Code Playgroud)

我尝试使用这里提到的技巧首先将行转换为 hstore,但这样做的问题是没有保留列排序......所以这个查询:

SELECT json_agg(avals(hstore(data_rows))) …
Run Code Online (Sandbox Code Playgroud)

sql arrays postgresql json postgresql-9.4

5
推荐指数
1
解决办法
3848
查看次数

用空值替换空字符串

我正在将一个庞大的表按计数汇总到一个新表中,在该表中我想将所有空字符串更改为NULL,并同时对一些列进行类型转换。我通读了一些帖子,但找不到查询,这使我可以在单个查询中跨所有列进行查询,而无需使用多个语句。

让我知道是否可以遍历所有列,并将单元格替换为具有null的空字符串。

参考:如何使用SQL Server将空格转换为空值?

string postgresql null replace plpgsql

4
推荐指数
1
解决办法
6574
查看次数

标签 统计

postgresql ×2

arrays ×1

json ×1

null ×1

plpgsql ×1

postgresql-9.4 ×1

replace ×1

sql ×1

string ×1