[英]How may I copy the same rows for each value in one column?
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 我需要在Postgresql或R中执行此操作
One option is separate_rows
if the 'id' is string
一种选择是
separate_rows
如果“身份证”是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
如果“ id”是
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: 您可以在PostgreSQL中这样做:
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. 基本上,您可以在文本字段之外创建一个数组,然后使用
unnest
获得所需的结果。
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()
: 在Postgres中,您只需要使用
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. 这假定您的列实际上是作为数组存储在Postgres中的。 If it is a string, you can do something similar, but it requires more string manipulation.
如果它是字符串,则可以执行类似的操作,但是需要更多的字符串操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.