Skip to content
Advertisement

Single query to split out data of one column, into two columns, from the same table based on different criteria [SQL]

I have the following data in a table, this is a single column shown from a table that has multiple columns, but only data from this column needs to be pulled into two column output using a query:

Required result: distinct values based on the first 13 characters of the data, split into two columns based on “long data”, and “short data”, BUT only giving the first 13 characters in output for both columns:

Something like:

I would also like to query/”scan” the table only once if possible. I can’t get any of the SO examples modified to make such a query work.

Advertisement

Answer

This is quite ugly, but doable. As a starter, you need a column that defines the order of the rows – I assumed that you have such a column, and that is called id.

Then you can select the distinct texts, put them in separate groups depending on their length, and finally pivot:

If you are content with ordering the records by the string column itself, it is a bit simpler (and, for your sample data, it produces the same results):

Demo on DB Fiddle:

shortData   | longData     
:---------- | :------------
1 DEC20 DDD | 1 JUL20 DDD80
1 JAN21 DDD | 1 JUL20DDDD40
1 JUL20 DDD | 1 JUL20DDDD80
null        | 1 JUN20 DDD50
null        | 1 JUN20DDDD50
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement