gpt4 book ai didi

sql - 生成带有列值的 json 作为 json 字典键

转载 作者:行者123 更新时间:2023-11-29 12:27:25 25 4
gpt4 key购买 nike

我正在使用 postgres 9.2,我正在尝试构建一个以特定格式生成 json 的查询。我已经非常接近一个简单的 json_agg 表达式,但现在我无法继续前进。

我有一个简单的三表模式,定义是:

CREATE TABLE project (
id INTEGER PRIMARY KEY,
name varchar(128) NOT NULL,
UNIQUE (name)
);

CREATE TABLE test (
id INTEGER PRIMARY KEY,
name varchar(128) NOT NULL,
project_id integer,
FOREIGN KEY (project_id) REFERENCES project(id),
);

CREATE TABLE data (
id INTEGER PRIMARY KEY,
date_entered timestamp with time zone NOT NULL,
data json NOT NULL,
test_id integer,
FOREIGN KEY (test_id) REFERENCES test(id)
);

像这样插入一些数据后:

INSERT INTO project (id, name) VALUES (0, 'my_project');
INSERT INTO test (id, name, project_id) VALUES (0, 'test0', 0);
INSERT INTO data (date_entered, data, test_id) VALUES (TIMESTAMP WITH TIME ZONE '2014-04-15T09:34:41.454999 z', '["some", "data"]', 0);
INSERT INTO test (id, name, project_id) VALUES (1, 'test1', 0);
INSERT INTO data (date_entered, data, test_id) VALUES (TIMESTAMP WITH TIME ZONE '2014-04-15T09:34:41.454999 z', '["some", "data"]', 1);

我想构建一个返回的查询:

{
"test0": {
"first_data": "2014-04-15 09:35:10.394+00",
"data_points": 1
},
"test1": {
"first_data": "2014-04-15 09:35:10.394+00",
"data_points": 1
}
}

我最接近这个解决方案的是这个查询:

SELECT
json_agg(data) as data
FROM (
SELECT
test.name as test_name,
min(data.date_entered) as first_data,
count(data.id) as data_points
FROM test
INNER JOIN data on data.test_id = test.id
INNER JOIN project on test.project_id = project.id
WHERE project.name = 'my_project'
GROUP BY test.name
) as data;

返回这个:

[
{
"test_name":"test0",
"first_data":"2014-04-15 09:34:41.454999+00",
"data_points":1
},
{
"test_name":"test1",
"first_data":"2014-04-15 09:34:41.454999+00",
"data_points":1
}
]

我尝试了 row_to_json 和 array_to_json 的各种奇怪用法,但我似乎无法将 test_name 值转换为外部字典中的键。

这可能吗?我在滥用 postgres 的 json 生成函数吗?

最佳答案

通过使用应用程序语言jsonifying,您确实做得更好。话虽如此,这里有一个丑陋的字符串连接解决方案

SQL Fiddle

select
(format(
'{"%s": {"first_data": "%s", "data_points": %s}}',
test.name,
min(data.date_entered),
count(data.id)
))::json as data
from test
inner join data on data.test_id = test.id
inner join project on test.project_id = project.id
where project.name = 'my_project'
group by test.name

关于sql - 生成带有列值的 json 作为 json 字典键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24400997/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com