[英]Postgresql join on json array
我正在嘗試編寫一個涉及 JSON 數組連接的查詢。 以下是表格
提案表:
id details
1 {units: [1, 2]}
2 {units: [1]}
單位表:
id DMA_ID
1 1
2 2
DMA表:
id name
1 SOLAPUR
2 PUNE
Output:
DMA_NAME, Count of proposals
SOLAPUR 2
PUNE 1
我的一些嘗試是,
SELECT
dma.name,
count(
CASE
WHEN EXISTS p.id from proposals_proposal p where (p.details->>'units')::jsonb->>u.unit_id is not null then 1
ELSE 0
)
FROM signs_dma dma JOIN signs_unit u ON dma.id=u.dma_id;
任何幫助表示贊賞。 提前致謝!
您可以使用下一個查詢:
SELECT DMA.name, COUNT(*) PROPOSAL_COUNT
FROM DMA
JOIN UNITS ON DMA.id=UNITS.dma_id
JOIN PROPOSAL ON to_jsonb(UNITS.id) <@ (PROPOSAL.details->'UNITS')
GROUP BY DMA.name;
這完成了工作
with base_proposal as (select id, jsonb_array_elements(details->'units') unit_id, created from proposals_proposal)
select
TRIM(dma.name) DMA, count(distinct bp.id) Proposals
from base_proposal bp
join signs_unit unit on unit.unit_id=bp.unit_id
join signs_dma dma on unit.dma_id = dma.id
where bp.created between {{start_date}} and {{end_date}}
group by TRIM(dma.name) order by count(distinct bp.id);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.