postgres表选择多列并将结果(列)动态转换为行-将列转换为行

1cklez4t  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(515)

我有以下类型的表(损坏)结构

Rowid    damageTypeACount      damageTypeBCount damageTypeCCount
  1        23                     44              33

而且我还需要读取这些表行,结果是(title,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

上面的查询按预期工作,但我想知道是否有可能在一个select语句中将列转换成行

vjrehmav

vjrehmav1#

可以使用横向联接取消连接:

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() :

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

相关问题