Postgres 表选择多列并将结果(列)动态转换为行 - 将列转置为行
Posted
技术标签:
【中文标题】Postgres 表选择多列并将结果(列)动态转换为行 - 将列转置为行【英文标题】:Postgres table selecting multiple columns and dynamically converting the result (column) into row - transposing column to rows 【发布时间】:2020-07-10 13:40:36 【问题描述】:我有一个如下类型的表(Damage)结构
Rowid damageTypeACount damageTypeBCount damageTypeCCount
1 23 44 33
而且我还需要读取这些表行,结果为(标题、id 是手动设置的),有点将列转换为行,但具有附加属性
id damagecountsum label
1 23 Damage Type A
2 44 Damage Type B
3 33 Damage Type C
我做了以下查询,它有效,但想知道是否有更好的方法
SELECT 1 as id,
damageTypeACount as damagecount,
"Damage Type A Count" as label
FROM Damage where rowId=1
UNION ALL
SELECT 2 as id,
damageTypeBCount as damagecount,
"Damage Type B Count" as label
FROM Damage where rowId=1
UNION ALL
SELECT 3 as id,
damageTypeCCount as damagecount,
"Damage Type C Count" as label
FROM Damage where rowId=1
上述查询按预期工作,但我想知道是否可以在单个选择语句中将列转换为行
【问题讨论】:
【参考方案1】:您可以使用横向连接进行反透视:
select x.*
from damage d
cross join lateral (values
(d.rowId, d.damageTypeACount, 'Damage Type A'),
(d.rowId, d.damageTypeBCount, 'Damage Type B'),
(d.rowId, d.damageTypeCCount, 'Damage Type C')
) as x(id, damagecount, label)
这会将原始id
重新影响到每个生成的行。你也可以用row_number()
生成新的id:
select row_number() over(order by id, label) id, x.*
from damage d
cross join lateral (values
(d.rowId, d.damageTypeACount, 'Damage Type A'),
(d.rowId, d.damageTypeBCount, 'Damage Type B'),
(d.rowId, d.damageTypeCCount, 'Damage Type C')
) as x(rowId, damagecount, label)
如果需要,您可以使用where
子句过滤结果集:
where d.rowId = 1
【讨论】:
谢谢。这样可行。我稍微修改了要求,相同的查询是否有效?以上是关于Postgres 表选择多列并将结果(列)动态转换为行 - 将列转置为行的主要内容,如果未能解决你的问题,请参考以下文章