【问题标题】:PostgreSQL: Compare and change values in the same column based on conditionsPostgreSQL:根据条件比较和更改同一列中的值
【发布时间】:2022-01-09 13:16:12
【问题描述】:

我有表格中的数据:

Name   Category  my_value
Ana    A         42
Ana    B         33
Bob    A         33
Bob    B         33
Carla  A         42
Carla  B         33

我希望相同的姓名发生以下情况:

  • 当 A 和 B 共享相同的值时,A 没有与之关联的值(在 col my_alue 中)。
  • 当 A 和 B 不同时,A 保留其值,而 B 没有与之关联的值(在 col my_value 中)。

我尝试过:

select *,
    case when Category = 'A' and Category = 'B' 
        then my_value = null
        else my_value
        end as "Value A (corrected)"
from my_table

显然错误...如果值不同,我不确定如何实现将 B 设置为 null 的条件。以及如何通过这里实现一个组来比较同名的类别...

理想情况下,这是我在 之后的输出(在同一列中更改,因为其中每个名称都有更多类别,即 C、D、E... - 只需要更改 A 和 B )

Name   Category  Value
Ana    A         42                      
Ana    B                                 
Bob    A                                 
Bob    B         33                                       
Carla  A         42    
Carla  B                                   

【问题讨论】:

    标签: sql postgresql null case


    【解决方案1】:

    在另一行是 A/B 恭维的地方加入自身:

    select
      t1.Name,
      t1.Category,
      case
        when t1.my_value = t2.my_value and t1.Category = 'A' then null
        when t1.my_value != t2.my_value and t1.Category = 'B' then null
        else t1.my_value
      end as my_value
    from my_table t1
    left join my_table t2 on t2.Name = t1.Name
      and t2.Category != t1.Category
      and t2.Category in ('A', 'B')
      and t1.Category in ('A', 'B')
    

    live demo

    如果 t1 的类别为“A”而 t2 的类别为“B”或反之亦然且名称相同,则连接到 t2。

    【讨论】:

    • 我要使用哪些关键字来详细了解您采用的 t1 和 t2 方法?
    • @Joehat 术语t1t2别名left join 是一个外连接(即使另一个表中没有匹配的行也会成功)。这是 self join 的示例(表连接到自身)。
    猜你喜欢
    • 2022-11-04
    • 1970-01-01
    • 1970-01-01
    • 2019-04-06
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    相关资源
    最近更新 更多