将一个值从数组连接到每个结果行

时间:2018-11-22 20:07:57

标签: postgresql

我想从表中选择数据,并从数组中为每个结果行分配一个值。

例如给出了包含以下产品数据的表格

product
-------
car
bike
elephant

和类似的数组

string_to_array('0.8, 0.6, 0.9', ',')

我想要一张这样的桌子

product | value
---------------
bike        0.8
car         0.6
elephant    0.9

有什么想法可以轻松解决这个问题吗?

类似这样的东西

WITH data_table AS (
  SELECT
      pr.id
    , pr.name
  FROM
    products pr
  ORDER BY pr.id
  LIMIT 20
)
SELECT 
    data_table.name
  , multipliers[row_number() over(order by data_table.id)]::numeric * data_table.id AS multiplied_value
 FROM 
     data_table
   , string_to_array('0.8, 0.6, 0.9, 0.65, 0.34, 0.67, 0.85, 0.12, 0.45, 0.76, 0.68, 0.98, 1.23, 0.69, 0.86, 1.11, 0.75, 1.02, 0.3, 0.79', ',') multipliers
 ORDER BY multiplied_value DESC
 LIMIT 20

1 个答案:

答案 0 :(得分:0)

假设应通过按名称排序来定义行的顺序,则可以使用以下命令:

select name, n[rn] as value
from (
   select name, row_number() over (order by name) as rn,
          string_to_array('0.8, 0.6, 0.9', ',') as n
   from the_table
) t