How to get info from VARCHAR column and create new column out of it

与世无争的帅哥 提交于 2019-12-11 10:25:34

问题


I have a problem that I can't figure out.

I have the table where it has column template_name, in every template, it ends with _US, _EE (aka country). I have to get that part to a new column that is Country.

Example data:

Template_name            Country
Party_package_US         US or USA
PARTY_Package_GB         GB or England
Random_temp_DE           DE or Germany

The output to the new column can be just the three last characters.

I don't know what kind of query I have to do to get that result.

Okay now, what can I do get that result to the new column in table?

   UPDATE #silverpop_header
    SET MARKET_AREA = a.template_name
    FROM  #silverpop_header pop
    join dw.f_CRM a
    ON   pop.template_name = a.TEMPLATE_NAME
    left join (
    select 
    RIGHT(RTRIM(Template_name), 2) country
    from dw.f_CRM )

It is on Sybase


回答1:


If you just need the last two characters

SELECT 
SUBSTRING(Template_name,-2) AS 'Country'
FROM TABLE;

EDIT: Or as mentioned in the comments:

SELECT
RIGHT(Template_name,2) AS 'Country'
FROM TABLE;



回答2:


Another way to handle non-2-digit country code.

SELECT Template_name, SUBSTRING_INDEX(Template_name, '_', -1) Country
FROM tbl;

To make this as a full demo. Let me post the full SQLs and output:

SQL:

-- Data prepraration
create table tbl(template_name varchar(200));
insert into tbl values
('Party_package_US'),
('PARTY_Package_GB'),
('Random_temp_DE');
SELECT * FROM tbl;

-- Needed query
SELECT Template_name, SUBSTRING_INDEX(Template_name, '_', -1) Country
FROM tbl;

Output:

mysql> SELECT * FROM tbl;
+------------------+
| template_name    |
+------------------+
| Party_package_US |
| PARTY_Package_GB |
| Random_temp_DE   |
+------------------+
3 rows in set (0.00 sec)

mysql>
mysql> -- Needed query
mysql> SELECT Template_name, SUBSTRING_INDEX(Template_name, '_', -1) Country
    -> FROM tbl;
+------------------+---------+
| Template_name    | Country |
+------------------+---------+
| Party_package_US | US      |
| PARTY_Package_GB | GB      |
| Random_temp_DE   | DE      |
+------------------+---------+
3 rows in set (0.00 sec)

mysql>
mysql> select version();
+-----------+
| version() |
+-----------+
| 5.7.8-rc  |
+-----------+
1 row in set (0.00 sec)


来源:https://stackoverflow.com/questions/35476054/how-to-get-info-from-varchar-column-and-create-new-column-out-of-it

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!