【问题标题】:how to count particular values from an array in postgresql如何从postgresql中的数组中计算特定值
【发布时间】:2020-10-19 21:54:18
【问题描述】:

我有一个名为“用户”的表,其中包含详细信息或 user_id 和 product_item_code。

例如:

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

我要数一下这些product_item_code 556、990、623。重复了多少次。

我正在寻找一个查询来给我如下的输出

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

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

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

请告诉我如何获得上述输出。 提前致谢

【问题讨论】:

  • 与你的问题无关,但count(1)实际上比count(*)

标签: sql arrays postgresql select count


【解决方案1】:

您可以使用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

【讨论】:

    【解决方案2】:

    使用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)
    

    【讨论】:

      【解决方案3】:

      无需取消嵌套。假设给定的项目在给定的数组中从未出现两次,您可以枚举派生表中的值,与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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-06
        • 1970-01-01
        • 2020-01-26
        • 2012-07-18
        • 1970-01-01
        • 1970-01-01
        • 2023-03-13
        相关资源
        最近更新 更多