쉼표로 구분 된 열 데이터를 추가 열로 분할
열에 쉼표로 구분 된 데이터가 있습니다.
Column
-------
a,b,c,d
이 출력을 얻기 위해 쉼표로 구분 된 데이터를 여러 열로 분할하고 싶습니다.
Column1 Column2 Column3 Column4
------- ------- ------- -------
a b c d
이것이 어떻게 달성 될 수 있습니까?
CSV의 필드 수가 일정하면 다음과 같이 할 수 있습니다.
select a[1], a[2], a[3], a[4]
from (
select regexp_split_to_array('a,b,c,d', ',')
) as dt(a)
예를 들면 :
=> select a[1], a[2], a[3], a[4] from (select regexp_split_to_array('a,b,c,d', ',')) as dt(a);
a | a | a | a
---+---+---+---
a | b | c | d
(1 row)
CSV의 필드 수가 일정하지 않으면 다음과 같이 최대 필드 수를 얻을 수 있습니다.
select max(array_length(regexp_split_to_array(csv, ','), 1))
from your_table
그런 다음 a[1], a[2], ..., a[M]
쿼리에 적합한 열 목록을 작성하십시오. 따라서 위의 내용이 최대 6을 제공했다면 다음을 사용합니다.
select a[1], a[2], a[3], a[4], a[5], a[6]
from (
select regexp_split_to_array(csv, ',')
from your_table
) as dt(a)
원하는 경우이 두 쿼리를 하나의 함수로 결합 할 수 있습니다.
예를 들어 다음 데이터를 제공합니다 (마지막 행의 NULL).
=> select * from csvs;
csv
-------------
1,2,3
1,2,3,4
1,2,3,4,5,6
(4 rows)
=> select max(array_length(regexp_split_to_array(csv, ','), 1)) from csvs;
max
-----
6
(1 row)
=> select a[1], a[2], a[3], a[4], a[5], a[6] from (select regexp_split_to_array(csv, ',') from csvs) as dt(a);
a | a | a | a | a | a
---+---+---+---+---+---
1 | 2 | 3 | | |
1 | 2 | 3 | 4 | |
1 | 2 | 3 | 4 | 5 | 6
| | | | |
(4 rows)
구분 기호는 간단한 고정 문자열이므로 string_to_array
대신 사용할 수도 있습니다 regexp_split_to_array
.
select ...
from (
select string_to_array(csv, ',')
from csvs
) as dt(a);
Thanks to Michael for the reminder about this function.
You really should redesign your database schema to avoid the CSV column if at all possible. You should be using an array column or a separate table instead.
split_part()
does what you want in one step:
SELECT split_part(col, ',', 1) AS col1
, split_part(col, ',', 2) AS col2
, split_part(col, ',', 3) AS col3
, split_part(col, ',', 4) AS col4
FROM tbl;
Add as many lines as you have items in col
(the possible maximum). Columns exceeding data items will be empty strings (''
).
You can use split function.
SELECT
(select top 1 item from dbo.Split(FullName,',') where id=1 ) Column1,
(select top 1 item from dbo.Split(FullName,',') where id=2 ) Column2,
(select top 1 item from dbo.Split(FullName,',') where id=3 ) Column3,
(select top 1 item from dbo.Split(FullName,',') where id=4 ) Column4,
FROM MyTbl
'program story' 카테고리의 다른 글
함수의 자바 스크립트 선택적 인수 (0) | 2020.12.03 |
---|---|
짧은 시간 동안 .NET 가비지 수집 방지 (0) | 2020.12.03 |
Java에서 숫자를 거듭 제곱하기 (0) | 2020.12.03 |
fgetcsv가 mac 형식의 csv 파일로 끝나는 줄을 읽지 못합니다. 더 나은 솔루션이 있습니까? (0) | 2020.12.02 |
쓰기 손실, 데이터 가용성과 같은 요인에 대비하여 기본 데이터 저장소로서 ElasticSearch의 안정성 (0) | 2020.12.02 |