1

I have the following example table:

 || *Column 1* || *Column 2* || *Column 3* || *Column 4* || 
 ||     a      ||   null     ||     b      ||     a      || 
 ||     b      ||     f      ||    null    ||     f      ||
 ||   null     ||     a      ||     a      ||     b      ||

The result table has to be:

 || *Column 1* || *Column 2* ||
 ||     a      ||     b      ||
 ||     b      ||     f      ||
 ||     a      ||     b      ||

Thanks!

6
  • are there any chances that all columns have difference values? Commented Apr 17, 2013 at 8:44
  • Let me get this right. Your new Column 1 is the 1st and 2nd value of old Column 1 and 3rd of old Coulmn 2, and new Column 2 is the 1st of Column 3 and 2nd and 3rd of Column 4 Commented Apr 17, 2013 at 8:45
  • I would do it with a script of some sort. Select all values from first table, do some script magic to sort out duplicates and null values, then insert into the second table. Doing it with queries or procedures only seems like a pain in the ... Commented Apr 17, 2013 at 8:46
  • and what if I have a in col1 and b in col3? Commented Apr 17, 2013 at 8:51
  • If in the first column there is a null value, then it has to be replaced with the first next not null value from the other columns. So, this problem is not about 2nd or 3rd columns. I need some kind of general solution. Commented Apr 17, 2013 at 9:05

2 Answers 2

4
SELECT one,
    CASE WHEN one != two THEN two
        WHEN one != three THEN three
        WHEN one != four THEN four END AS two
FROM (  SELECT COALESCE(col1, col2, col3, col4) AS one,
            COALESCE(col2, col3, col4, col1) AS two,
            COALESCE(col3, col4, col1, col2) AS three,
            COALESCE(col4, col1, col2, col3) AS four
        FROM four_columns) AS h

Can't think of a simplier solution considering what result you wish in the example.

This obviously obsoletes cases where these 4 columns have more than 2 different letters, due to only 2 columns existing. But it won't show duplicates and will not show NULL if there is at least 2 unique letters.

Sign up to request clarification or add additional context in comments.

2 Comments

Why are you using CASE ? What if I only use COALESCE()?
Else on the third row in your example you'd get double a and no b. Basicly it makes sure you don't get double letters and more importantly, you don't fetch the same column value twice.
1

If I understand you well, what you want to do is merge Column 3 with Column 1, and Column 4 with Column 2.

The following problem has already been answered on this post.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.