簡體   English   中英

從 Bigquery 中的字符串中提取日期和時間

[英]Extracting Days and Timings from a String in Bigquery

我正在使用 bigquery 從字符串中提取用戶的計划數據。

字符串看起來像這樣:

{"0,1,2,3,4,5,6":[["11:00","21:30"]]}

-> 這意味着用戶計划每周 7 天從上午 11:00 到晚上 9:30

{"0,1,2,3,6":[["11:00","21:30"]],"4,5":[["11:00","22:30"]]}

-> 這意味着用戶將在周六至周三的上午 11:00 至晚上 9:30 以及周五的上午 11:00 至晚上 10:30 在線

我想把它分成三列,天數和開始/結束時間。 到目前為止,我已經能夠使用 REGEXP_Extract Function 獲得第一個示例所需的數據。

開始時間 時間結束
0,1,2,3,4,5,6 11:00 21:30

不知道如何 go 為第二個例子做這件事。

這是我使用過的查詢。

select 
name,
periods, 
REGEXP_EXTRACT(periods, "{\"(.*)\":.*") as Days,
REGEXP_EXTRACT(periods, "\\[\\[\"(.*)\",") as Start_time,
REGEXP_EXTRACT(periods, ",\"(.*)\"\\]\\]") as  end_time,

from `projectid.dataset.table` where is_active_cache=1 limit 100

您可以考慮以下。

WITH sample_table AS (
  SELECT '{"0,1,2,3,4,5,6":[["11:00","21:30"]]}' schedule UNION ALL
  SELECT '{"0,1,2,3,6":[["11:00","21:30"]],"4,5":[["11:00","22:30"]]}'
)
SELECT days, start_time, end_time
  FROM sample_table, UNNEST (REGEXP_EXTRACT_ALL(schedule, r'"([0-9,]*)":')) days WITH offset
  JOIN UNNEST(REGEXP_EXTRACT_ALL(schedule, r'\[\["(\d{2}:\d{2})"')) start_time WITH offset USING (offset)
  JOIN UNNEST(REGEXP_EXTRACT_ALL(schedule, r'"(\d{2}:\d{2})"]]')) end_time WITH offset USING (offset);

查詢結果

在此處輸入圖像描述

您可以使用以下查詢:

select
  name,
  periods,
  REGEXP_EXTRACT(periods, "{\"([^\"]*)\":.*") as Days,
  REGEXP_EXTRACT(periods, "\\[\\[\"(.*)\",") as Start_time,
  REGEXP_EXTRACT(periods, ",\"(.*)\"\\]\\]") as End_time,
from `projectid.dataset.table`
where is_active_cache = 1
  and REGEXP_CONTAINS(periods, "{\"[^\"]*\":[\\[\\[\"[^\"]*\",\"[^\"]*\"\\]\\]]}")
limit 100

其中"{\"([^\"]*)\":.*"匹配以{"開頭的字符串,后跟一組不包含"的字符,后跟": ,然后是任意數量的字符,直到字符串結束。

另一種代碼更簡潔的方法

select null as days, null as start_time, null as end_time from unnest([1]) where false 
union all
select * except(schedule, pos) from (
  select schedule, part, div(offset, 3) pos, mod(offset, 3) as col
  from your_table, unnest(regexp_extract_all(schedule, r'"([^"]*?)"')) part with offset
)
pivot (any_value(part) for col in (0,1,2))          

如果應用於您問題中的示例數據 - output 是

在此處輸入圖像描述

暫無
暫無

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

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