1

Given such table:

+-----------+-----------+-----------+-----------+
|    id     |     A     |     B     |     C     |
+-----------+-----------+-----------+-----------+
|    100    |     1     |    NULL   |    NULL   |
+-----------+-----------+-----------+-----------+
|    101    |    NULL   |     2     |    NULL   |
+-----------+-----------+-----------+-----------+
|    102    |    NULL   |    NULL   |     3     |
+-----------+-----------+-----------+-----------+
|    103    |     4     |    NULL   |    NULL   |
+-----------+-----------+-----------+-----------+
|    104    |    NULL   |    NULL   |     5     |
+-----------+-----------+-----------+-----------+

Is there a way to make a query which combines the multiple rows into one to avoid empty fields?

Example result:

+-----------+-----------+-----------+
|     A     |     B     |     C     |
+-----------+-----------+-----------+
|     1     |     2     |     3     |
+-----------+-----------+-----------+
|     4     |    NULL   |     5     |
+-----------+-----------+-----------+

To notice how:

  • Each row contains only one value for the fields (and so A or B or C)
  • There isn't a field which can help grouping all fields of an entry
  • An entry can have a different number of fields (an entry could have A, B and C as fields, while another could have only A and C or similar).

Not sure if anything can be done about this?

Any suggestion is really appreciated!

1 Answer 1

1

You want to condense the data. One method is union all with a trick:

select max(a), max(b), max(c)
from ((select a as val, null as b, null as c, row_number() over (order by id) as seqnum
       from t
       where a is not null
      ) union all
      (select null, b, null, row_number() over (order by id) as seqnum
       from t
       where b is not null
      ) union all
      (select null, null, c, row_number() over (order by id) as seqnum
       from t
       where c is not null
      ) 
     ) abc
group by seqnum;
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.