【发布时间】:2021-03-25 14:45:29
【问题描述】:
我正在尝试使用MySql 获取以下逻辑。我将用 psedocode 编写,然后向您展示我所做的以及预期的结果。
when Country = 'Spain'
take the Value where the Property = Status A
else take the Value where Property = Status B
我有两张表,我将向您展示它们的组成,但是由于数据敏感性,数据不会真实。
表 1
|ID | Country|
:---|-------:|
|123| Spain |
|456| Italy |
表 2
|ID |Property Code | Value|
|:--|:------------:|-----:|
|123| Property A | Red |
|456| Property A | Grey |
|456| Property B | Blue |
预期结果
|ID |Country | Value|
|:--|:------------:|-----:|
|123| Spain | Red |
|456| Italy | Blue |
当前使用的代码
select distinct
t1.ID ,t1.Country
,case when t1.Country = 'Spain' and t2.PropertyCode = 'Property A' then t2.Value
when t1.Country <> 'Spain' and t2.PropertyCode = 'Property B' then t2.Value else '' end as Value
from table1 t1
left join table2 t2 on t1.ID = t2.ID
电流输出
|ID |Country | Value|
|:--|:------------:|-----:|
|123| Spain | Red |
|456| Italy | Blue |
|456| Italy | |
有人可以帮忙吗?我不想得到重复的值,我很确定我在正确使用情况下使用了这种情况。我希望每个ID 有一行,如上面的预期结果所示。
谢谢。
【问题讨论】:
-
简化您的生活为西班牙创建一个选择并为非西班牙联合一个选择