我正在加入3个表并获取某些列的重复数据。我想将数据合并到一行。
以下是数据库结构和数据。
CREATE TABLE customers (
id integer NOT NULL,
fname character varying(50),
lname character varying(50)
);
COPY customers (id, fname, lname) FROM stdin;
1 Thomas Jefferson
2 Benjamin Franklin
\.
CREATE TABLE customers_products (
id integer NOT NULL,
customers_id integer,
products_id integer,
account_info json
);
COPY customers_products (id, customers_id, products_id, account_info) FROM stdin;
1 1 1 {"account_number":"000001", "date":"05/28/15"}
2 1 2 {"account_number":"000002", "date":"05/28/15"}
3 2 1 {"account_number":"000003", "date":"05/28/15"}
4 2 3 {"account_number":"000004", "date":"05/28/15"}
\.
CREATE TABLE products (
id integer NOT NULL,
name character varying(128)
);
COPY products (id, name) FROM stdin;
1 checking
2 savings
3 credit card
\.
这是我正在使用的查询。
SELECT
c.id,
c.fname,
c.lname,
p.name,
cp.account_info
FROM
customers c
INNER JOIN
customers_products cp
ON
c.id = cp.customers_id
INNER JOIN
products p
ON
p.id = cp.products_id
这是结果数据集。
如何将数据集重新分成两行,并将帐户信息合并为一行?这是我想要最终得到的数据结构。
[
{
"id": 1,
"fname": "Thomas",
"lname": "Jefferson",
"account_info": [
{
"name": "checking",
"account_number":"000001",
"date":"05/28/15"
},
{
"name": "savings",
"account_number":"000002",
"date":"05/28/15"
}
]
},
{
"id": 2,
"fname": "Benjamin",
"lname": "Franklin",
"account_info": [
{
"name": "checking",
"account_number":"000003",
"date":"05/28/15"
},
{
"name": "credit card",
"account_number":"000004",
"date":"05/28/15"
}
]
}
]
解决方案是:
SELECT
c.id,
c.fname,
c.lname,
string_agg(p.name, ', '),
json_agg(cp.account_info)
FROM
customers c
INNER JOIN
customers_products cp
ON
c.id = cp.customers_id
INNER JOIN
products p
ON
p.id = cp.products_id
GROUP BY
c.id, c.fname, c.lname
ORDER BY
c.id;