簡體   English   中英

如何計算 postgresql 中數組中的特定值

[英]how to count particular values from an array in postgresql

我有一個名為“用戶”的表,其中包含詳細信息或 user_id 和 product_item_code。

前任:

Select * from Users limit 5;
+----+---------+---------------------------+
| id | user_id |     product_item_code     |
+----+---------+---------------------------+
|  1 |     123 | {556,772,945}             |
|  2 |     124 | {556,965,945,990}         |
|  3 |     125 | {772, 435, 990, 556}      |
|  4 |     126 | {556, 623, 842}           |
|  5 |     127 | {842, 990, 556, 623, 745} |
+----+---------+---------------------------+

我想數一下這些product_item_code 556、990、623。重復了多少次。

我正在尋找一個查詢來給我一個 output 如下所示

+-------------------+-------+
| product_item_code | count |
+-------------------+-------+
|               556 |     5 |
|               990 |     3 |
|               623 |     2 |
+-------------------+-------+

我已經嘗試了以下代碼,但無法獲得預期的 output。

select count(1) from Users where ARRAY[556, 990, 623] @> ANY(product_item_code);

請讓我知道如何獲得上述 output。 提前致謝

您可以使用unnest的數組值,然后對它們進行計數,例如:

select u, count(*) from users
join lateral unnest(product_item_code) u on true
where
u in(556, 990, 623)
group by u
order by count(*) desc

無需取消嵌套。 假設給定的項目在給定的數組中從未出現兩次,您可以枚舉派生表中的值,使用any()連接並聚合:

select p.code, count(*) cnt
from (values (556), (990), (223)) p(code)
inner join users u on p.code = any(u.product_item_code)
group by p.code

使用unnest將 arrays 轉換為行,然后group by product_item_code以獲取計數:

=# with expand as (
  select unnest(product_item_code) as product_item_code
    from users
)
select product_item_code, count(*)
  from expand
 where product_item_code in (556, 990, 623)
 group by product_item_code
 order by count(*) desc;

 product_item_code | count
-------------------+-------
               556 |     5
               990 |     3
               623 |     2
(3 rows)

暫無
暫無

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

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