我有包含指定列的表:
id - bigint
decision - varchar(80)
type - varchar(258)
我想做一個選擇查詢,它在結果中回傳類似這樣的內容(id,decisionsValues with counts as json, type):
id decisions type
1 {"firstDecisionsValue":countOfThisValue, "secondDecisionsValue": countOfThisValue} entryType
我聽說我可以嘗試使用 json_agg 但它不允許 COUNT 方法,嘗試使用 json_agg 進行查詢:
SELECT ac.id,
json_agg(ac.decision),
ac.type
FROM myTable ac
GROUP BY ac.id, ac.type;
但以此結束(對于 id 1 的條目,firstDecisionsValue 出現兩次,secondDecisionsValue 出現一次):
id decisions type
1 {"firstDecisionsValue", "firstDecisionsValue", "secondDecisionsValue"} entryType
最小的可重復示例
CREATE TABLE myTable
(
id bigint,
decisions varchar(80),
type varchar(258)
);
INSERT INTO myTable
VALUES (1, 'firstDecisionsValue', 'myType');
INSERT INTO myTable
VALUES (1, 'firstDecisionsValue', 'myType');
INSERT INTO myTable
VALUES (1, 'secondDecisionsValue', 'myType');
你能給我提供一些如何按預期制作的提示嗎?
1, {"fistDecisionsValue":2, "secondDecisionsValue":1}, entryType
uj5u.com熱心網友回復:
你可以試試這個
SELECT a.id, jsonb_object_agg(a.decisions, a.count), a.type
FROM
( SELECT id, type, decisions, count(*) AS count
FROM myTable
GROUP BY id, type, decisions
) AS a
GROUP BY a.id, a.type
在dbfiddle 中查看結果。
uj5u.com熱心網友回復:
首先,您應該計算之后id, type, decisions每個決策的計數,您應該使用它jsonb_object_agg來創建 JSON。
演示
with data as (
select
ac.id,
ac.type,
ac.decisions,
count(*)
from
myTable ac
group by
ac.id,
ac.type,
ac.decisions
)
select
d.id,
d.type,
json_object_agg(d.decisions, d.count)
from
data d
group by
d.id,
d.type
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/388199.html
標籤:PostgreSQL的
