How get all matching positions in a string?

前端 未结 3 1853
轻奢々
轻奢々 2021-01-29 14:46

I have a column flag_acumu in a table in PostgreSQL with values like:

\'SSNSSNNNNNNNNNNNNNNNNNNNNNNNNNNNNSNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN\'         


        
3条回答
  •  醉话见心
    2021-01-29 15:04

    In Postgres 9.4 or later you can conveniently use unnest() in combination with WITH ORDINALITY:

    SELECT *
    FROM   dh12 d
    JOIN   unnest(string_to_array(d.flag_acumu, NULL))
              WITH ORDINALITY u(elem, the_pos) ON u.elem = 'S'
    WHERE  d.flag_acumu LIKE '%S%'  -- optional, see below
    ORDER  BY d.codn_conce, u.the_pos;
    

    This returns one row per match. WHERE d.flag_acumu LIKE '%S%' is optional to quickly eliminate source rows without any matches. Pays if there are more than a few such rows.

    Detailed explanation and alternatives for older versions:

    • PostgreSQL unnest() with element number

提交回复
热议问题