[英]SQL convert column by different condition in select statement
I have a table that contains a string address.我有一个包含字符串地址的表。 I want to select the column text in specific format.我想选择特定格式的列文本。 However, the column contains different format and it requires different rules.但是,该列包含不同的格式,并且需要不同的规则。 For example,if the column contain words like 'SHOP', it will select the wording start with 'SHOP'.例如,如果该列包含诸如“SHOP”之类的词,它将选择以“SHOP”开头的词。 If the column contains words like 'BOX', it will select the wording after 'BOX'.如果该列包含像“BOX”这样的词,它会选择“BOX”之后的词。
tableA
__________________________
|columna |address |
__________________________
|a1234 |ddsa SHOP LG123|
__________________________
|4322 |SADA BOX 12-42 |
__________________________
|4632 |123123 ADV 2313|
__________________________
I want something like this.我想要这样的东西。 Select by different condition in different rules in same column.在同一列的不同规则中按不同条件选择。
SELECT
ta.columna,
if CHARINDEX('SHOP',ta.address) > 0
RIGHT(ta.address, len(ta.address) - charindex('SHOP', ta.address)+1) AS unit_addr,
if CHARINDEX('BOX',ta.address) > 0
RIGHT(ta.address, len(ta.address) - charindex('BOX', ta.address)-8) AS unit_addr,
if CHARINDEX('ADV',ta.address) > 0
RIGHT(ta.address, charindex('ADV', ta.address)-3) AS unit_addr
FROM
tableA ta
So the final table will be this.所以决赛桌将是这样。
tableA
__________________________
|columna |address |
__________________________
|a1234 |SHOP LG123 |
__________________________
|4322 |12-42 |
__________________________
|4632 |2313 |
__________________________
You need to use a Case expression.您需要使用 Case 表达式。 Assuming the logic above does what you need, this sort of thing should provide the result in the structure you want...假设上面的逻辑满足您的需求,这种事情应该以您想要的结构提供结果......
select ta.columna,
case
when CHARINDEX('SHOP',ta.address) > 0 then
RIGHT(ta.address, len(ta.address) - charindex('SHOP', ta.address)+1)
when CHARINDEX('LIGHTBOX',ta.address) > 0 then
RIGHT(ta.address, len(ta.address) - charindex('LIGHTBOX', ta.address)-8)
when CHARINDEX('ADV',ta.address) > 0 then
RIGHT(ta.address, charindex('ADV', ta.address)-3)
end as address
from tablea ta
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.