0

We have data sorted like the format below. The first column is our system numbering, the second column is a back end system numbering, and the third column signifies that the rows with a ParentCol value actually below to the matching row of Col1. (So item 20 has two additional parts, item 30 and item 50.)

Col1      Col2      ParentCol
10        100       NULL
20        200       NULL
30        201       20
40        300       NULL
50        202       20
10        400       NULL
...

This is just a small example - there can sometimes be hundreds of rows per order. The application isn't handling this situation well from the standpoint of viewing the data in the UI. Ideally, I would like to have the content sorted like this, with our ID number (Col1) being the primary sorting, but recognizing that the back-end ID number (Col2) should immediately follow when there is a ParentCol value matching our ID:

Col1      Col2      ParentCol
10        100       NULL
10        400       NULL
20        200       NULL
30        201       20
50        202       20
40        300       NULL

Using T-SQL, how would I write a query that returns the data as I need it? Because of the various numbering schemes and possible valid duplicate values in our numbering scheme, Col1, (but not the back-end column, Col2), I haven't been able to figure this one out.

Thank you,

Scott

1 Answer 1

2
SELECT *
FROM @t 
ORDER BY CASE WHEN ParentID IS NULL THEN col1 ELSE ParentID END, col2
Sign up to request clarification or add additional context in comments.

1 Comment

+1, also, using COALESCE instead of CASE: … ORDER BY COALESCE(ParentID, col1), col2.

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.