PostgreSQL:根据条件比较和更改同一列中的值
PostgreSQL: Compare and change values in the same column based on conditions
我有以下形式的数据:
Name Category my_value
Ana A 42
Ana B 33
Bob A 33
Bob B 33
Carla A 42
Carla B 33
我希望相同的 Name 发生以下情况:
- 当 A 和 B 共享相同的值时,A 没有关联值(在列 my_alue 中)。
- 当 A 和 B 不同时,A 保留其值而 B 没有关联值(在列 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
在另一行是 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 进行连接,反之亦然且名称相同。
我有以下形式的数据:
Name Category my_value
Ana A 42
Ana B 33
Bob A 33
Bob B 33
Carla A 42
Carla B 33
我希望相同的 Name 发生以下情况:
- 当 A 和 B 共享相同的值时,A 没有关联值(在列 my_alue 中)。
- 当 A 和 B 不同时,A 保留其值而 B 没有关联值(在列 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
在另一行是 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 进行连接,反之亦然且名称相同。