SQL Server – Arrange Rows in Paired Sequence

sql server

I have a database table in which a row has its matching pair. Checkpoint A has a matching pair checkpoint B. Every IN status has a matching OUT status. To match these exists a 'related_id' column with the id of the row it is related to.
Normally the table order can be as follows:

id | registration_no | checkpoint | related_id | status
 1      H2080              A            2          IN
 2      H2080              B            1          OUT
 3      H2081              A            8          IN
 4      H2070              A            6          IN
 5      H2087              A            7          IN          
 6      H2070              B            4          OUT          
 7      H2087              B            5          OUT
 8      H2081              B            3          OUT

but instead i would like it to be ordered in this way

id | registration_no | checkpoint | related_id | status
 1      H2080              A            2          IN
 2      H2080              B            1          OUT
 3      H2081              A            8          IN
 8      H2081              B            3          OUT
 4      H2070              A            6          IN          
 6      H2070              B            4          OUT          
 5      H2087              A            7          IN
 7      H2087              B            5          OUT

in which the leading checkpoint A is immediately followed by the matching checkpoint B by somehow using the related_id to tell which columns are paired together. So the rows will alternate between A->B then A->B and so on.

I hope i managed to explain the question.

Any help is greatly appreciated. thank you

Best Answer

You can use this ORDER BY:

SELECT  ...
FROM ...
ORDER BY
    CASE checkpoint WHEN 'A' THEN id 
                    WHEN 'B' THEN related_id
    END,
    checkpoint ;