简体   繁体   中英

How to EXTRACT from long string by SQL BigQuery

By using Bigquery SQL (#standardSQL) , I want to extract 0.1e1 and 0.55e6 to another column and convert data type float -> int64.

   \nsub_total:\n- !ruby/object:BigDecimal 18:0.1e1\n- !ruby/object:BigDecimal 18:0.55e6\ninvoice_number:\n- \n- '

My expected:

String | 1 | 550000

Use regexp_extract_all() to extract the strings. Then convert to a float and then to an integer to sum them:

select t.*,
       (select sum(cast(cast(val as float64) as int64))
        from unnest(regexp_extract_all(str, '[0-9][.][0-9]*e[0-9]+')) val
       )
from (select '   \nsub_total:\n- !ruby/object:BigDecimal 18:0.1e1\n- !ruby/object:BigDecimal 18:0.55e6\ninvoice_number:\n- \n- ' as str
     ) t;

EDIT:

If you want to extract these into an array, just use:

select t.*,
       (select array_agg(cast(cast(val as float64) as int64))
        from unnest(regexp_extract_all(str, '[0-9][.][0-9]*e[0-9]+')) val
       ) as int_array
from (select '   \nsub_total:\n- !ruby/object:BigDecimal 18:0.1e1\n- !ruby/object:BigDecimal 18:0.55e6\ninvoice_number:\n- \n- ' as str
     ) t

If you want these in separate columns, just use array operations.

EDIT:

If you want the values in separate columns:

select t.*, ar[safe_ordinal(1)] as col1, 
       ar[safe_ordinal(2)] as col2
from (select t.*,
             array_agg(cast(cast(val as float64) as int64)) as ar
      from (select '   \nsub_total:\n- !ruby/object:BigDecimal 18:0.1e1\n- !ruby/object:BigDecimal 18:0.55e6\ninvoice_number:\n- \n- ' as str
           ) t
     ) t

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM