簡體   English   中英

如何為一列中的每個值復制相同的行?

[英]How may I copy the same rows for each value in one column?

如何在一行中復制每個值的行

假設我們有像這樣的列:

---------------------
record time     id
---------------------
1      12:00    [1,2,3]
2      12:01    [4,5,6,7]
3      12:07    [8,9]

我想得到如下結果:

---------------------
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

我需要在Postgresql或R中執行此操作

一種選擇是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

如果“ 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))

您可以在PostgreSQL中這樣做:

SELECT DISTINCT record, time, unnest(translate(id, '[]', '{}'):: int[]) AS ids
FROM tbl  
ORDER BY record, time, ids;

基本上,您可以在文本字段之外創建一個數組,然后使用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

演示

在Postgres中,您只需要使用unnest()

select t.record, t.time, unnest(t.id) as id
from t;

這假定您的列實際上是作為數組存儲在Postgres中的。 如果它是字符串,則可以執行類似的操作,但是需要更多的字符串操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM