SQL - 根据特定列值创建两个新行条目

时间:2017-12-12 10:04:37

标签: sql postgresql

我有一个包含一些地址数据的数据库表。我的问题是有些行有两个housenumber条目,如下所示:

'8, 8A'
'12,14'

我想做的是:

  • 将此行拆分为两个单独的行
  • 新行每个都有特定的房屋号
  • 删除包含两个条目的旧行
  • 对于其他列,新行应具有与之前相同的值

housenumber列是一个文本字段,因为可以添加诸如A' A' B'等。 我想知道在sql中是否有任何方法可以做到这一点,所以感谢任何帮助。

修改

以下是我的表格: enter image description here

3 个答案:

答案 0 :(得分:2)

你可以这样做

数据

CREATE TABLE address
(house_number VARCHAR(20),
 street   VARCHAR(100));

INSERT INTO address  VALUES ('8, 8A', 'High Street');
INSERT INTO address VALUES ('12, 14', 'New Street');
INSERT INTO address VALUES ('1', 'First Street');

<强>解决方案

SELECT TRIM(adr_split.house_number) AS house_number, adr.street
  FROM address adr, UNNEST(STRING_TO_ARRAY(adr.house_number, ',')) adr_split(house_number);

<强>输出

house_number    street
8               High Street
8A              High Street
12              New Street
14              New Street
1               First Street

在使用旧数据替换此输出方面,您可以执行此操作

CREATE TABLE new_address
(house_number VARCHAR(20),
 street   VARCHAR(100));

INSERT INTO new_address
SELECT TRIM(adr_split.house_number) AS house_number, adr.street
  FROM address adr, UNNEST(STRING_TO_ARRAY(adr.house_number, ',')) adr_split(house_number);

DROP TABLE address;

ALTER TABLE new_address RENAME TO address;

现在,地址表将包含您期望的数据。

输出

SELECT * FROM address;

    house_number    street
    8   High Street
    8A  High Street
    12  New Street
    14  New Street
    1   First Street

答案 1 :(得分:0)

怎么样:

select left(col_1, charindex(',', col_1))
  from table_1
 where charindex(',', col_1) > 0
 union 
select substring(col_1, charindex(',', col_1), 255)
  from table_1
 where charindex(',', col_1) > 0
 union 
select col_1
  from table_1
 where charindex(',', col_1) = 0

答案 2 :(得分:0)

不知道所有列很难说,但基本上是想法:

制备

std::string

检查:

t=# with a(i,addr) as (values(1,$$'8, 8A'
'12,14'$$))
select * into so4 from a;
SELECT 1

动作:

t=# select * from so4;
 i |  addr
---+---------
 1 | '8, 8A'+
   | '12,14'
(1 row)

检查:

t=# with a as (select i, unnest(string_to_array(addr,chr(10))) from so4 group by i, addr)
, i as (insert into so4 select * from a)
delete from so4 using a where a.i = so4.i and a.unnest <> so4.addr
;
DELETE 1