How may I copy rows for each value in one column
Let's say that we have column like:
---------------------
record time id
---------------------
1 12:00 [1,2,3]
2 12:01 [4,5,6,7]
3 12:07 [8,9]
And I would like to get result like:
---------------------
record time id
---------------------
1 12:00 1
2 12:00 2
3 12:00 3
4 12:01 4
5 12:01 5
...
9 12:07 9
I need to do this in Postgresql or R
One option is separate_rows
if the 'id' is string
library(tidyverse)
df1 %>%
separate_rows(id) %>%
filter(id != "") %>%
mutate(record = row_number())
# record time id
#1 1 12:00 1
#2 2 12:00 2
#3 3 12:00 3
#4 4 12:01 4
#5 5 12:01 5
#6 6 12:01 6
#7 7 12:01 7
#8 8 12:07 8
#9 9 12:07 9
If the 'id' is a list
df1 %>%
unnest
df1 <- structure(list(record = 1:3, time = c("12:00", "12:01", "12:07"
), id = c("[1,2,3]", "[4,5,6,7]", "[8,9]")), class = "data.frame",
row.names = c(NA, -3L))
You could do it in PostgreSQL like so:
SELECT DISTINCT record, time, unnest(translate(id, '[]', '{}'):: int[]) AS ids
FROM tbl
ORDER BY record, time, ids;
Basically, you create an array out of your text field, and then use unnest
to get your desired result.
record | time | ids
--------+----------+-----
1 | 12:00:00 | 1
1 | 12:00:00 | 2
1 | 12:00:00 | 3
2 | 12:01:00 | 4
2 | 12:01:00 | 5
2 | 12:01:00 | 6
2 | 12:01:00 | 7
3 | 12:07:00 | 8
3 | 12:07:00 | 9
In Postgres, you would just use unnest()
:
select t.record, t.time, unnest(t.id) as id
from t;
This assumes that your column is actually stored as an array in Postgres. If it is a string, you can do something similar, but it requires more string manipulation.
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.