简体   繁体   English

如何计算 postgresql 中数组中的特定值

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

I have a table called "User" where it has the details or user_id and product_item_code.我有一个名为“用户”的表,其中包含详细信息或 user_id 和 product_item_code。

ex:前任:

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} |
+----+---------+---------------------------+

I want to count these product_item_code 556, 990, 623. How many times it's been repeated.我想数一下这些product_item_code 556、990、623。重复了多少次。

I am looking for a query to give me an output like below我正在寻找一个查询来给我一个 output 如下所示

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

I have tried the below code but couldn't get the expected output.我已经尝试了以下代码,但无法获得预期的 output。

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

Please let me know how can I get the above output.请让我知道如何获得上述 output。 Thanks in advance提前致谢

You can use unnest array values and then count them, like:您可以使用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

No need to unnest.无需取消嵌套。 Assuming that a given item never appears twice in a given array, you can enumerate the values in a derived table, join with any() , and aggregate:假设给定的项目在给定的数组中从未出现两次,您可以枚举派生表中的值,使用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

Use unnest to turn the arrays into rows and then group by product_item_code to get your counts:使用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