如何在postgresql中计算数组中的特定值
我有一个名为“User”的表,其中包含详细信息或User\u id和product\u item\u代码 例: 我想数一数这些产品项目代码556990623。重复了多少次 我正在寻找一个查询,给我一个如下输出如何在postgresql中计算数组中的特定值,sql,arrays,postgresql,select,count,Sql,Arrays,Postgresql,Select,Count,我有一个名为“User”的表,其中包含详细信息或User\u id和product\u item\u代码 例: 我想数一数这些产品项目代码556990623。重复了多少次 我正在寻找一个查询,给我一个如下输出 +-------------------+-------+ | product_item_code | count | +-------------------+-------+ | 556 | 5 | | 990 |
+-------------------+-------+
| product_item_code | count |
+-------------------+-------+
| 556 | 5 |
| 990 | 3 |
| 623 | 2 |
+-------------------+-------+
我尝试了以下代码,但无法获得预期的输出
select count(1) from Users where ARRAY[556, 990, 623] @> ANY(product_item_code);
请让我知道如何获得上述输出。
提前感谢您可以使用
unest
数组值,然后对它们进行计数,如:
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
您可以使用
unest
数组值,然后对它们进行计数,如:
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
使用
unest
将数组转换为行,然后使用按产品\u项目\u代码分组
获取计数:
=# 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)
使用
unest
将数组转换为行,然后使用按产品\u项目\u代码分组
获取计数:
=# 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)
不必担心。假设给定项在给定数组中从不出现两次,则可以枚举派生表中的值,使用
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
不必担心。假设给定项在给定数组中从不出现两次,则可以枚举派生表中的值,使用
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
与您的问题无关,但是
count(1)
实际上比count(*)慢
与您的问题无关,但是count(1)
实际上比count(*)慢