【问题标题】:How to get a specific value which dependets on different values of a data feed?如何获得取决于数据馈送的不同值的特定值?
【发布时间】: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 有一行,如上面的预期结果所示。

谢谢。

【问题讨论】:

  • 简化您的生活为西班牙创建一个选择并为非西班牙联合一个选择

标签: mysql output case


【解决方案1】:

嘿,我设法找到了解决方案:

  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

where (t1.Country = 'Spain' and t2.PropertyCode = 'Property A'
   or t1.Country <> 'Spain' and t2.PropertyCode = 'Property B')

希望这可以帮助那里的其他人! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-17
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-24
    相关资源
    最近更新 更多