0

In sql-server, There are three column in same table,i want to make Column_C from Column_A and Column_B i want to get in same table in sql

 Column_A  Column_B Column_C
    1,2,3,4      2,3
     1,2,3        1



    Column_A  Column_B Column_C
     1,2,3,4      2,3  1,4
     1,2,3        1    2,3 
Biddut
  • 399
  • 5
  • 15

3 Answers3

1

If you use Postgres, you can install the intarray extension, then the solution is as simple as:

select column_a, 
       column_b, 
       array_to_string(
          string_to_array(column_a,',')::int[] - string_to_array(column_b,',')::int[]
       , ',') as column_c
from badly_designed_table

despite the horrible design.

string_to_array(column_a,',')::int[] converts the string to an array.

The intarray extensions provides the - operator that removes elements from the first array that are contained in the second.

array_to_string() then converts the array back to a string.

a_horse_with_no_name
  • 497,550
  • 91
  • 775
  • 843
0

I'm very unsure what the actual table looks like or the columns for that matter... But I'll give you a general response for now and you can let me know if you need something else:

SELECT (ColumnA - ColumnB) AS Column C
FROM tablename 

But since your table isn't normalized, this is very confusing. As well, you should never store multiple values separated by a comma in your table, because you can do it, but it'll make SQL development SOOOO much harder.

0

This should do it. It replaces Column_B's string present in Column_A with an empty string. It also deals with potential double commas and leading/trailing commas

SELECT Column_A,
       Column_B,
       LTRIM(
         RTRIM(
           REPLACE(
             REPLACE(Column_A,
                     Column_B,
                     ''),
             ',,',
             ','),
           ','),
         ',') AS Column_C
  FROM Table1

This is correct for Oracle SQL. If you are using a different DBMS, I think you just need to use the corresponding TRIM syntax.

Alex Zen
  • 886
  • 7
  • 9