簡體   English   中英

在PostgreSQL中對數組項進行條件查詢

[英]Query with condition on array items in PostgreSQL

我想選擇一個表中的行,其中數組列中的一定數量的項目滿足比較條件(> = n)。 不使用嵌套也可以嗎?

unnest()是對數組中已過濾元素進行計數的自然方法。 但是,您可以將其隱藏在這樣的sql函數中:

create or replace function number_of_elements(arr int[], val int)
returns bigint language sql
as $$
    select count(*)
    from unnest(arr) e
    where e > val;
$$;

with test(id, arr) as (
    values 
        (1, array[1,2,3,4]),
        (2, array[3,4,5,6]))
select id, arr, number_of_elements(arr, 3)
from test;

 id |    arr    | number_of_elements 
----+-----------+--------------------
  1 | {1,2,3,4} |                  1
  2 | {3,4,5,6} |                  3
(2 rows)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM