简体   繁体   English

查询以分隔,然后计算PostgreSQL中逗号分隔值的字段

[英]Query to separate, then count a field of comma separated values in postgresql

I have a table in postgresql that starts like this: 我在postgresql中有一个表,其开始如下:

car_id  part_ids     total_inventory
------  --------     ----------
10134   101,506,589  50
12236   201,506,101  20
78865   201,399,304  10

I'm trying to write a query and/or view that will separate each of the part_ids on the comma, count the sum total_inventory together for each part_id, and then include all of the part_ids in a single column like this: 我正在尝试编写一个查询和/或视图,该查询和/或视图将逗号分隔每个part_id,将每个part_id的总total_inventory计数在一起,然后将所有part_id包括在这样的单个列中:

part_ids total_inventory
-------- ----------
101      70
506      70   
589      50
201      30
399      10
304      10

I've tried using unnest(string_to_array) on the part_ids column to get the end result - but haven't had too much luck. 我试过在part_ids列上使用unnest(string_to_array)以获得最终结果-但运气还不算太高。

Anyone have any ideas? 有人有想法么? Thanks for helping! 感谢您的帮助!

PS this is my first question - any recommendations/edits please let me know 附言:这是我的第一个问题-任何建议/编辑,请让我知道

Something like this should work 这样的事情应该工作

select p.part_id, 
       sum(t.total_inventory) as total_inventory
from parts t
  cross join lateral unnest(string_to_array(part_ids, ',')::int[]) as p(part_id)
group by p.part_id

Online example: http://rextester.com/NVTCG56767 在线示例: http : //rextester.com/NVTCG56767

Try this: 尝试这个:

WITH X AS 
(
    SELECT car_id, UNNEST(REGEXP_SPLIT_TO_ARRAY(part_ids, ',')) AS part_ids, total_inventory FROM parts
)
SELECT part_ids, SUM(total_inventory) AS total_inventory FROM X GROUP BY part_ids
ORDER BY total_inventory DESC;

In the first step i create a temporary table to hold unnested values. 第一步,我创建一个临时表来保存未嵌套的值。

Then i group part_ids and sum their related total_inventory. 然后,我将part_id分组并对其相关的total_inventory求和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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