1

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

1
  • Unrelated to your question, but count(1) is actually slower than count(*) Commented Jun 29, 2020 at 18:27

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.