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

o2gm4chl  于 2021-08-01  发布在  Java
关注(0)|答案(3)|浏览(338)

我有一个名为“user”的表,其中包含详细信息或用户id和产品项代码。
前任:

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

我要数一数这些商品的代码是556990623。重复了多少次。
我正在寻找一个查询,给我一个如下输出

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

我尝试了下面的代码,但无法获得预期的输出。

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

请让我知道如何才能得到上述输出。提前谢谢

58wvjzkj

58wvjzkj1#

你可以用 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
8oomwypt

8oomwypt2#

不用担心。假设给定项在给定数组中从不出现两次,则可以枚举派生表中的值,join with 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
2skhul33

2skhul333#

使用 unnest 将数组转换为行,然后 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)

相关问题