简体   繁体   中英

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.

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.

I am looking for a query to give me an output like below

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

I have tried the below code but couldn't get the expected 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. Thanks in advance

You can use unnest array values and then count them, like:

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:

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:

=# 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM