SQL - re.split:BY逗号那么空格

时间:2017-10-21 21:20:45

标签: sql

我想将以下字符串拆分为City,Province,Postal Code。 非常感谢你的帮助!!!!

描述:用逗号分割,然后按空格分割一次。

A = 'Vaughan, ON L6D 9X0'

结果:

(Vaughan, ON, L6D9X0)

尝试:

re.split(',|/s[1]', A)

3 个答案:

答案 0 :(得分:0)

如果您正在使用from selenium.webdriver.support.ui import Select select = Select(driver.find_element_by_name('name')) select.select_by_index(index) select.select_by_visible_text("text") select.select_by_value(value) const express = require('express'); const request = require('request'); const cheerio = require('cheerio') const app = express(); const port = 5000; app.get('/streak/:user', function(req, res) { request('https://github.com/users/' + req.params.user + '/contributions', function(error, response, body) { if (error) { console.log(error); res.sendStatus(500); return; } processContrib(res, body); }); }); function processContrib(res, body) { var $ = cheerio.load(body); var data = []; $('svg').find('rect').each(function(index, element) { data.push({ count: parseInt($(element).attr('data-count')), date: new Date($(element).attr('data-date')) }) }); var yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); data = data.sort(function(a, b) { return new Date(b.date) - new Date(a.date); }).filter(function(el) { return el.date.getTime() <= yesterday.getTime(); }); var streakCount = 0; for (var i = 0; i < data.length; i++) { if (data[i].count == 0) { break; } streakCount++ } res.status(200).json({ streak: streakCount }); } app.listen(port, function() { console.log('listening on port', port); }); ,那么您可以使用Microsoft()&amp; SQL Server()函数查找特定的SUBSTRING索引分割CHARINDEX值。

Char

期望输出:

string

答案 1 :(得分:0)

试试这个,

这会将值选为行,也许您可​​以转动 cte C2 相同,以便将其作为列

WITH CTE
AS
(
  SELECT
    1 Seq,
    'Vaughan, ON L6D 9X0' "Txt"

  UNION ALL

  SELECT
    Seq+1 "Seq",
    Txt = CASE WHEN Txt LIKE '% %'
              THEN LTRIM(RTRIM(SUBSTRING(Txt,CHARINDEX(' ',Txt),LEN(Txt))))
            ELSE NULL END
    FROM CTE
      WHERE ISNULL(txt,'')<>''
),C2
AS
(
SELECT
  CASE Seq
    WHEN 1 THEN 'City'
    WHEN 2 THEN 'Province'
    ELSE 'PostalCode' END "Head",
  CASE Seq
    WHEN 1
      THEN SUBSTRING(Txt,1,CHARINDEX(',',Txt)-1)
    WHEN 2 
      THEN SUBSTRING(Txt,1,CHARINDEX(' ',Txt)-1)
    ELSE Txt END "Txt"
  FROM CTE
    WHERE Seq<4
)
SELECT
  *
  FROM C2;

如果有多行需要以相同的方式解析,则可以在1st CTE的select语句中给出相同的内容,在这种情况下,可能需要更改第一个选择中Seq的逻辑。如上所述,输出如下

Sample Output

答案 2 :(得分:0)

使用Postgres,你可以使用:

select split_part(a, ',', 1) as city,
       left(trim(split_part(a,',',2)), strpos(trim(split_part(a,',',2)), ' ')),
       substr(trim(split_part(a,',',2)) as province, strpos(trim(split_part(a,',',2)), ' ') + 1) as postal_code
from the_table;

使用派生表可以使这一点更具可读性:

select city,
       left(second_part, strpos(second_part, ' ')) as province,
       substr(second_part, strpos(second_part, ' ') + 1) as postal_code
from (
  select split_part(a, ',', 1) as city,
         trim(split_part(a, ',', 2)) as second_part
  from the_table
) t