PostgreSQL表格转换

huangapple go评论74阅读模式
英文:

PostgreSQL table transformation

问题

我已经将表格转换为以下格式:

id 年份 字段1 字段2 字段3
1 2000 10 20 30
1 2001 100 200 300

我希望转换后的版本如下:

id 字段 value_2000 value_2001
1 字段1 10 100
1 字段2 20 200
1 字段3 30 300

感谢任何意见!我已经能够使用unnest函数将列名转换为行,但在获取相应数值方面遇到了一些问题。

英文:

I have the table in below format :

id year column1 column2 column3
1 2000 10 20 30
1 2001 100 200 300

I want the transformed version to be like -

id Field value_2000 value_2001
1 column1 10 100
1 column2 20 200
1 column3 30 300

Appreciate any input!

I was able to take the column names in rows using unnest function. But facing some issues with taking the corresponding values.

答案1

得分: 0

你通常会在侧向连接中将行数据转化为列数据,然后使用条件聚合将其转化为目标数据集。

select t.id, x.col,
    max(x.val) filter(where t.year = 2000) val_2000,
    max(x.val) filter(where t.year = 2001) val_2001
from mytable t
cross join lateral ( values
    ( 'column1', column1 ),
    ( 'column2', column2 ),
    ( 'column3', column3 )
) x(col, val)
group by t.id, x.col
order by t.id, x.col

请注意,这仅适用于固定的列和年份列表 - 否则,您需要使用动态SQL(即在SQL中生成查询文本,然后执行它),这是一种完全不同的方法。

英文:

You would typically unpivot the rows to columns in a lateral join, then pivot to the target dataset with conditional aggregation.

select t.id, x.col,
    max(x.val) filter(where t.year = 2000) val_2000,
    max(x.val) filter(where t.year = 2001) val_2001
from mytable t
cross join lateral ( values
    ( 'column1', column1 ),
    ( 'column2', column2 ),
    ( 'column3', column3 )
) x(col, val)
group by t.id, x.col
order by t.id, x.col

Note that this works for a fixed list of columns and of years - otherwise you need dynamic SQL (ie generate the query text in SQL, then execute it), which is a rather different beast.

huangapple
  • 本文由 发表于 2023年3月8日 17:22:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671275.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定