HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Always fetch 3 records in a particular order

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
orderalwaysfetchrecordsparticular

Problem

I have a query which gets 3 books (ABC1,ABC2,ABC3) and their details. I need them in a particular order for pivoting so I have a Row number column for the same. People read none/some/all books.

Table:

StudentID|||BookName|||RowNumber
1000|||ABC1|||27
1000|||ABC2|||31
1000|||ABC3|||28
1005|||ABC2|||28
1005|||ABC3|||20
1005|||ABC1|||25
1006|||ABC1|||12
1006|||ABC2|||14
1006|||ABC3|||15


So my data would be something like the above. I need for each student, ABC1,ABC2,ABC3 should come in the order AND Rownumber to be UPDATED in descending order. So for student 1000:

ABC1||27,ABC2||28,ABC3||31


For student 1005:

ABC1||20,ABC2||25,ABC3||28


For 1006: no change (they're already in the right order).

I have all the above data into a temp table and master data into another temp table. I'm trying to write an update statement but nothing works as expected. I need some help.

Solution

CREATE TABLE #t(StudentID INT, BookName VARCHAR(10), RowNumber INT);

INSERT #t(StudentID,BookName,RowNumber) VALUES
(1000,'ABC1',27),    (1000,'ABC2',31),    (1000,'ABC3',28),
(1005,'ABC2',28),    (1005,'ABC3',20),    (1005,'ABC1',25),
(1006,'ABC1',12),    (1006,'ABC2',14),    (1006,'ABC3',15);

;WITH x AS 
(
  SELECT StudentID, BookName, RowNumber, 
   rn1 = ROW_NUMBER() OVER (PARTITION BY StudentID ORDER BY BookName),
   rn2 = ROW_NUMBER() OVER (PARTITION BY StudentID ORDER BY RowNumber)
  FROM #t
)
SELECT x.StudentID, x.BookName, y.RowNumber
 FROM x INNER JOIN x AS y
  ON x.StudentID = y.StudentID
  AND x.rn1 = y.rn2
ORDER BY x.StudentID, x.rn1;
GO

DROP TABLE #t;


Results:

StudentID BookName RowNumber
--------- -------- ---------
1000 ABC1 27
1000 ABC2 28
1000 ABC3 31
1005 ABC1 20
1005 ABC2 25
1005 ABC3 28
1006 ABC1 12
1006 ABC2 14
1006 ABC3 15

Code Snippets

CREATE TABLE #t(StudentID INT, BookName VARCHAR(10), RowNumber INT);

INSERT #t(StudentID,BookName,RowNumber) VALUES
(1000,'ABC1',27),    (1000,'ABC2',31),    (1000,'ABC3',28),
(1005,'ABC2',28),    (1005,'ABC3',20),    (1005,'ABC1',25),
(1006,'ABC1',12),    (1006,'ABC2',14),    (1006,'ABC3',15);

;WITH x AS 
(
  SELECT StudentID, BookName, RowNumber, 
   rn1 = ROW_NUMBER() OVER (PARTITION BY StudentID ORDER BY BookName),
   rn2 = ROW_NUMBER() OVER (PARTITION BY StudentID ORDER BY RowNumber)
  FROM #t
)
SELECT x.StudentID, x.BookName, y.RowNumber
 FROM x INNER JOIN x AS y
  ON x.StudentID = y.StudentID
  AND x.rn1 = y.rn2
ORDER BY x.StudentID, x.rn1;
GO

DROP TABLE #t;

Context

StackExchange Database Administrators Q#116053, answer score: 7

Revisions (0)

No revisions yet.