簡體   English   中英

計算嵌套數組中多個列和單詞之間的匹配

[英]Count matches between multiple columns and words in a nested array

我先前的問題已解決。 現在,我需要開發一個相關但更復雜的查詢。

我有一張這樣的桌子:

id     description          additional_info
-------------------------------------------
123    games                XYD
124    Festivals sport      swim

我需要計算與數組匹配的次數,如下所示:

array_content varchar[] := {"Festivals,games","sport,swim"}

如果列descriptionadditional_info中的任何一個包含用逗號分隔的任何標簽,則我們將其計為1。因此,每個數組元素(由多個單詞組成)只能對總數貢獻1。

以上示例的結果應為:

id    RID    Matches
1     123    1
2     124    2

答案並不簡單,但要弄清您的要求卻比較困難:

SELECT row_number() OVER (ORDER BY t.id) AS id
     , t.id AS "RID"
     , count(DISTINCT a.ord) AS "Matches"
FROM   tbl t
LEFT   JOIN (
   unnest(array_content) WITH ORDINALITY x(elem, ord)
   CROSS JOIN LATERAL
   unnest(string_to_array(elem, ',')) txt
   ) a ON t.description ~ a.txt
       OR t.additional_info ~ a.txt
GROUP  BY t.id;

准確產生您想要的結果。
array_content是您搜索詞的數組。

這是如何運作的?

搜索項中外部數組的每個數組元素都是一個逗號分隔的列表。 通過取消嵌套兩次來分解奇數構造(將外部數組的每個元素轉換為另一個數組之后)。 例:

SELECT *
FROM   unnest('{"Festivals,games","sport,swim"}'::varchar[]) WITH ORDINALITY x(elem, ord)
CROSS  JOIN LATERAL
       unnest(string_to_array(elem, ',')) txt;

結果:

 elem            | ord |  txt
-----------------+-----+------------
 Festivals,games | 1   | Festivals
 Festivals,games | 1   | games
 sport,swim      | 2   | sport
 sport,swim      | 2   | swim

既然你要指望一次為每個外數組元素的比賽,我們生成與飛一個唯一的編號WITH ORDINALITY 細節:

現在我們可以在所需匹配的條件下將LEFT JOIN到此派生表:

   ... ON t.description ~ a.txt
       OR t.additional_info ~ a.txt

..並使用count(DISTINCT a.ord)獲得計數,即使多個搜索字詞匹配,每個數組也僅計數一次。

最后,我在row_number() OVER (ORDER BY t.id) AS id添加了神秘的id row_number() OVER (ORDER BY t.id) AS id假設它應該是序列號)。 Voilá。

正則表達式匹配( ~ )的注意事項與上一個問題相同:

暫無
暫無

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

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