I am trying to order a specific request, taking into account the next and previous records, but I cannot do this. I would like to order by number and letter, but if, for example, the last letter of number 1 is equal to one of the letters of number 2, I want to change the order so that the letter matches the next entry.
Create script and SQL fiddle demo
create table Parent ( id [bigint] IDENTITY(1,1), number bigint NOT NULL, PRIMARY KEY (id) ) GO create table Child ( id [bigint] IDENTITY(1,1), parentId BIGINT, letter VARCHAR(1) NOT NULL, PRIMARY KEY (id), UNIQUE (parentId, Letter), FOREIGN KEY (parentId) REFERENCES Parent(id) ) GO INSERT Parent (number) VALUES (1) INSERT Parent (number) VALUES (2) INSERT Parent (number) VALUES (3) INSERT Child (parentId, letter) VALUES (1, 'A') INSERT Child (parentId, letter) VALUES (1, 'C') INSERT Child (parentId, letter) VALUES (2, 'B') INSERT Child (parentId, letter) VALUES (2, 'C') INSERT Child (parentId, letter) VALUES (3, 'B') INSERT Child (parentId, letter) VALUES (3, 'D')
Current request
I am currently sorting with this query:
SELECT P.number, C.letter FROM Child C JOIN Parent P ON C.parentId = P.id ORDER BY P.number, C.letter
Current result set
number letter
Expected Result
To clarify what I really want to do, here is the expected result set (with switching C and B with number 2).
number letter
Other requirements and question
- It should work in SQL SERVER 2005 .
- There is a scenario that uses 3 letters per number, I am glad if it uses the best match.
- I am also interested in solutions for later versions of SQL Server (for training), but they do not answer my question.
Can someone point me in the right direction how to do this?