我有下表。
╔════════════════════╦════════════════════╦═════════════╗
║id ║arr1 ║arr2 ║
╠════════════════════╬════════════════════╬═════════════╣
║1 ║{1,2,3,4} ║{2,1,7} ║
║2 ║{0} ║{3,4,5} ║
╚════════════════════╩════════════════════╩═════════════╝
我想找出 arr1 中而不是 arr2 中的元素。
預期輸出
╔════════════════════╦════════════════════╗
║id ║diff ║
╠════════════════════╬════════════════════╣
║1 ║{3,4} ║
║2 ║{0} ║
╚════════════════════╩════════════════════╝
如果我有 2 個單獨的陣列,我可以執行以下操作:
select array_agg(elements)
from (
select unnest(array[0])
except
select unnest(array[3,4,5])
) t (elements)
但是我無法通過從我的表中選擇來集成此代碼以使其作業。任何幫助將不勝感激。謝謝!!
uj5u.com熱心網友回復:
我會為此撰寫一個函式:
create function array_diff(p_one int[], p_other int[])
returns int[]
as
$$
select array_agg(item)
from (
select *
from unnest(p_one) item
except
select *
from unnest(p_other)
) t
$$
language sql
stable;
然后你可以像這樣使用它:
select id, array_diff(arr1, arr2)
from the_table
更快的替代方法是安裝在intarray模塊和使用
select id, arr1 - arr2
from the_table
uj5u.com熱心網友回復:
您應該except為每個 id 和在該組之后使用每個組
演示
with diff_data as (
select id, unnest(arr1) as data
from test_table
except
select id, unnest(arr2) as data
from test_table
)
select id, array_agg(data order by data) as diff
from diff_data
group by id
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/380147.html
標籤:PostgreSQL的
