【问题标题】:Join rows if the same value in one column如果一列中的值相同,则连接行
【发布时间】:2018-10-31 09:51:46
【问题描述】:

有一个 Postgres 数据库,表有三列。数据结构在外部系统中,无法修改。

每个对象由三行表示(由列element_id标识-该列中具有相同值的行表示同一对象),例如:

key     value            element_id
-----------------------------------
status  active           1
name    exampleNameAAA   1
city    exampleCityAAA   1
status  inactive         2
name    exampleNameBBB   2
city    exampleCityBBB   2
status  inactive         3
name    exampleNameCCC   3
city    exampleCityCCC   3

我想获得描述每个对象的值对。它必须是namestatus

对于这个例子,输出应该是这样的:

exampleNameAAA   | active
exampleNameBBB   | inactive
exampleNameCCC   | inactive

解决这个问题的最佳方法是什么?

【问题讨论】:

    标签: sql postgresql entity-attribute-value


    【解决方案1】:

    您可以使用自联接

    select a.value as name,
           b.value as status
    from the_table a 
      join the_table b 
        on a.element_id = b.element_id 
       and b."key" = 'status'
    where a."key" = 'name';
    

    在线示例:https://rextester.com/NPJ5782

    【讨论】:

      猜你喜欢
      • 2013-03-03
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      相关资源
      最近更新 更多