Skip to content
Advertisement

Creating new data table on existing one

Hello I’ve got a question, how (if it possible), I can create new datatables with close same rows but if In column value is in string “/” for example

ID column_param column_sym column_value column_val2
First param_test1 ABC 11/12 test
Second param_test2 CDE 22/11 test
Third param_test3 EFG 44 teste
4’th param_test4 HIJ 33/22 test

And here if I have param_test1 and param_test4 and if in this column value has “/” I want to create 2 other rows but if I will not set param_test2 then it stay as it is and everything should be in new datatable. Is any way to create this? Thank you in advance.

Expected result:

ExpectedResult

Advertisement

Answer

  • As per Gordon’s answer, I’m not sure what should be done with the your ID column. I’ve replaced these with row numbers.
  • Depending on your version of MySQL/MariaDB, the ROW_NUMBER() window function may not be available. Depending on whether IDs in the output are necessary you may be able to simply omit this.
  • I’ve assumed the existence of a table called myNumbers which contains a single field num and is populated with positive integers from 1 to whatever you’re likely to need.

I’ve included more in the output that you asked for, which will hopefully help you understand what’s going on

SELECT
    ROW_NUMBER() OVER (ORDER BY d.ID, n.num) as NewID,
    d.ID as OriginalID,
    n.num as,
    d.column_param,
    d.column_sym,
    d.column_value as orig_value,
    CASE WHEN column_param = 'param_test2' THEN d.column_value
    ELSE substring_index(substring_index(d.column_value,'/',n.num),'/',-1) END as split_value,
    d.column_val2
FROM
    myData d
    JOIN myNumbers n on char_length(d.column_value)-char_length(replace(d.column_value,'/','')) >= n.num-1
WHERE
    n.num = 1 OR d.column_param <> 'param_test2'
ORDER BY
    d.ID,
    n.num

See this DB Fiddle (the columns output in a different order than I’ve specified, but I think that’s a DB Fiddle quirk).

If you only want to “split” say param_test1 and param_test4 rows the code above code could be amended as follows:

SELECT
    ROW_NUMBER() OVER (ORDER BY d.ID, n.num) as NewID,
    d.ID as OriginalID,
    d.column_param,
    d.column_sym,
    n.num,
    d.column_value as orig_value,
    CASE WHEN column_param NOT IN ('param_test1','param_test4') THEN d.column_value
    ELSE substring_index(substring_index(d.column_value,'/',n.num),'/',-1) END as split_value,
    d.column_val2
FROM
    myData d
    JOIN myNumbers n on char_length(d.column_value)-char_length(replace(d.column_value,'/','')) >= n.num-1
WHERE
    n.num = 1 OR d.column_param  IN ('param_test1','param_test4')
ORDER BY
    d.ID,
    n.num
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement