3

What I want to do should really be basic but for some reason I can't figure it out. Consider the following:

ID, COL1, COL2
1   'A'   NULL
1   NULL  'B'

I want to group on ID and 'squeeze out' the gaps and get:

ID, COL1, COL2
1   'A'   'B'

I'm probably having a black out as this sounds a very sqly problem/solution. This on a very large data set with many rows and columns so efficiency would be important

4
  • What if there's a third row 1, 'C', 'C'? Commented Oct 26, 2018 at 13:13
  • Sorry, this behavior is not clear to me. Please edit your answer and add this use case and your expected output. Commented Oct 26, 2018 at 14:14
  • Sorry my response above was incorrect and I'm on a phone and can't format the question correctly. Essentially what I'm trying to do is reduce the size of this data set which has been comprised from a few sources. For the above example I only need 2 rows. 1 row comprising of A,B and one C,C. kind of distinct on col1, col2 but ignoring nulls Commented Oct 27, 2018 at 7:35
  • My problem is: Can there be more rows with same ID with values != NULL. For example: ID 1, but three rows with col1 values = A, NULL, C. If so, what value as to be chosen: A or C or {A,C} or MAX... I understood that you want two resulting rows with A and C. Is this correct? So you jsut want to eliminate the NULL values? But if you have to columns: Both of yours and a third row [1CC], two possible results can happen: [1AB, 1CC] or [1AC, 1CB]. It would be important to know what is your expected result and what is the algorithm how to chose the right one. It is far more complicated with more rows Commented Oct 27, 2018 at 8:36

1 Answer 1

3

demo: db<>fiddle

You could simply use an aggregate function which "removes" NULL values. MAX doesn't chose NULL if there's another value for example:

SELECT 
    id, 
    MAX(col1) as col1, 
    MAX(col2) as col2
FROM my_table
GROUP BY id
Sign up to request clarification or add additional context in comments.

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.