Skip to content
Advertisement

sqlite – combine same field in 2 rows into 2 columns based on field value

I have a sqlite table with data similar to the following:

I’d like to get results that look like the following:

To explain, I’m trying to “combine” the id’s of each “pair” of records (in order) where “flag == 1”. Where the record has “flag == 0”, id2 should just be NULL. Also notice, since I have a odd number of records where “flag == 1” (in this example), the final one (id = 7) doesn’t have an additional record to pair with, so it too has an id2 field of NULL.

Is this possible via pure SQL (sqlite3 in this case)? I can obviously post-process the results in the host application, but was hoping to not have to.

*** EDIT ***

Adding the requested MRE…

Advertisement

Answer

You can do it with window functions MIN() and ROW_NUMBER():

See the demo.
Results:

id1 id2
1 null
2 null
3 5
4 null
6 null
7 null
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement