简体   繁体   中英

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'. If the column contains words like 'BOX', it will select the wording after '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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM