SQL Sting Split into Single Column

后端 未结 2 1201
深忆病人
深忆病人 2021-01-28 14:30

Very new to SQL but I require some help with something that I am sure is a simple fix.

I have a single column of data within a table called \'Produce\' where types of fr

2条回答
  •  北海茫月
    2021-01-28 14:48

    This can be done with pure SQL, no user written functions needed.

    SQL Server

    WITH
        fruittable
        AS
            (   SELECT 'Apple' fruit, 1 id
             UNION ALL
                SELECT 'Banana,Apple', 2
             UNION ALL
                SELECT 'Tomato,Grapefruit,Apple', 3
             UNION ALL
                SELECT 'Watermelon,Persimmons', 4
              ),
        split (fruit, id, leftover)
        AS
            (SELECT case when len(fruit) = 0 or fruit is null then null else left(fruit + ',',  charindex(',',fruit + ',') -1 ) end AS fruit
                  , id
                  , case when len(fruit) = 0 or fruit is null then null else right(fruit + ',', len(fruit) - charindex(',',fruit + ',') + 1) end as leftover
               FROM fruittable
             UNION ALL
             SELECT case when len(leftover) = 0 or leftover is null then null else left(leftover,  charindex(',',leftover) - 1) end AS fruit
                  , id
                  , case when len(leftover) = 0 or leftover is null then null else substring(leftover,  charindex(',',leftover) + 1, len(leftover)) end as leftover
               FROM split
              WHERE fruit IS NOT NULL)
    SELECT fruit, id
      FROM split where fruit is not null
      order by fruit, id;
    

    Oracle

    WITH
        fruittable
        AS
            (SELECT 'Apple' fruit, 1 id
               FROM DUAL
             UNION ALL
             SELECT 'Banana,Apple', 2
               FROM DUAL
             UNION ALL
             SELECT 'Tomato,Grapefruit,Apple', 3
               FROM DUAL
             UNION ALL
             SELECT 'Watermelon,Persimmons', 4
               FROM DUAL),
        split (fruit, id, leftover)
        AS
            (SELECT SUBSTR (fruit || ',', 1, INSTR (fruit || ',', ',') - 1) AS fruit
                  , id
                  , SUBSTR (fruit || ',', INSTR (fruit || ',', ',') + 1) AS leftover
               FROM fruittable
             UNION ALL
             SELECT SUBSTR (leftover, 1, INSTR (leftover, ',') - 1) AS fruit
                  , id
                  , SUBSTR (leftover, INSTR (leftover, ',') + 1) AS leftover
               FROM split
              WHERE fruit IS NOT NULL)
      SELECT fruit, id
        FROM split
       WHERE fruit IS NOT NULL
    ORDER BY fruit, id
    

提交回复
热议问题