如何解决如何获取取决于数据馈送的不同值的特定值?
我正在尝试使用 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
都有一行,如上面的预期结果所示。
谢谢。
解决方法
嘿,我设法找到了解决方案:
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')
希望这可以帮助那里的其他人! :)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。