This is the next question about Sorting based on the following and previous records in SQL
But now it is becoming a little more complicated, for example:
- If any letter from 1 matches any letter 2, I want to change the order so that the letter matches the next entry.
- If no matches are found, normal lettering should be performed.
- Identifiers are potentially unsuccessful, and records are not displayed in the correct order. [SQLFiddle Demo]
[Create script and SQL Fiddle demo]
create table Parent ( id [bigint] IDENTITY(1,2), number bigint NOT NULL, PRIMARY KEY (id) ) GO create table Child ( id [bigint] IDENTITY(1,2), parentId BIGINT, letter VARCHAR(1) NOT NULL, PRIMARY KEY (id), UNIQUE (parentId, Letter), FOREIGN KEY (parentId) REFERENCES Parent(id) ) GO DECLARE @ParentIdentity BIGINT INSERT Parent (number) VALUES (2) SET @ParentIdentity = @@IDENTITY INSERT Child (parentId, letter) VALUES (@ParentIdentity, 'C') INSERT Child (parentId, letter) VALUES (@ParentIdentity, 'B') INSERT Parent (number) VALUES (3) SET @ParentIdentity = @@IDENTITY INSERT Child (parentId, letter) VALUES (@ParentIdentity, 'D') INSERT Child (parentId, letter) VALUES (@ParentIdentity, 'B') INSERT Parent (number) VALUES (1) SET @ParentIdentity = @@IDENTITY INSERT Child (parentId, letter) VALUES (@ParentIdentity, 'C') INSERT Child (parentId, letter) VALUES (@ParentIdentity, 'A') GO
Current request
I am currently sorting with this query:
;WITH CTE AS ( SELECT id,ParentID,letter, ROW_NUMBER() OVER (ORDER BY ID) seq_id, ROW_NUMBER() OVER (PARTITION BY parentId ORDER BY ID) first_element, ROW_NUMBER() OVER (PARTITION BY parentId ORDER BY ID DESC) Last_element FROM Child ), CTE2 AS ( SELECT c1.id, c1.parentid, c1.letter, c2.parentid as c2parentid FROM CTE c1 INNER JOIN CTE c2 ON c1.last_element = 1 AND c2.first_element = 1 AND c1.seq_id + 1 = c2.seq_id ), CTE3 AS ( SELECT C.parentid, C.id FROM CTE2 INNER JOIN child C ON CTE2.c2parentid = C.parentid AND C.letter = CTE2.letter ) SELECT P.number, C.letter FROM Child C JOIN Parent P ON C.parentId = P.id LEFT JOIN CTE3 ON CTE3.id = C.id ORDER BY P.number, ISNULL(CTE3.id,0) DESC, C.letter
Current result set
number letter
Expected Result
To clarify what I really want to do, here is the expected result set:
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.
Can someone point me in the right direction how to handle this scenario?