Postgresql

如何根據提供的數據將同一列中的多行拆分為不同的列 postgres

  • July 7, 2022

所以這就是我所擁有的……

但我正在嘗試找到一種方法來獲得這種結果……

所以如果我能在查詢部分得到任何幫助……我仍然是 psql 的初學者,所以如果你也能解釋一下……謝謝

標準條件聚合(數據透視)查詢應該可以工作

SELECT
 t.id,
 t.name,
 MAX(t.children) FILTER (WHERE t.rn = 1) AS child1,
 MAX(t.age)      FILTER (WHERE t.rn = 1) AS age1,
 MAX(t.children) FILTER (WHERE t.rn = 2) AS child2,
 MAX(t.age)      FILTER (WHERE t.rn = 2) AS age2,
 MAX(t.children) FILTER (WHERE t.rn = 3) AS child3,
 MAX(t.age)      FILTER (WHERE t.rn = 3) AS age3
FROM (
   SELECT *,
     ROW_NUMBER() OVER (PARTITION BY t.id, t.name ORDER BY t.children) AS rn
   FROM YourTable t
) t
GROUP BY
 t.id,
 t.name;

db<>小提琴

引用自:https://dba.stackexchange.com/questions/314110