Share via

Order records based on value

Michael M.M. D'Angelo 176 Reputation points
2023-08-27T01:21:44.4833333+00:00

I have a table with data as below

Script:

CREATE TABLE [dbo].[ClassScore](
	[Id] [int] IDENTITY(1,1) NOT NULL,
	[StudentId] [int] NOT NULL,
	[SubjectId] [int] NOT NULL,
	[ClassScore] [decimal](38, 6) NULL,
 CONSTRAINT [PK_ClassScore] PRIMARY KEY CLUSTERED 
(
	[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET IDENTITY_INSERT [dbo].[ClassScore] ON 
GO
INSERT [dbo].[ClassScore] ([Id], [StudentId], [SubjectId], [ClassScore]) VALUES (1, 3071, 2007, CAST(83.099960 AS Decimal(38, 6)))
GO
INSERT [dbo].[ClassScore] ([Id], [StudentId], [SubjectId], [ClassScore]) VALUES (2, 3068, 2007, CAST(60.599990 AS Decimal(38, 6)))
GO
INSERT [dbo].[ClassScore] ([Id], [StudentId], [SubjectId], [ClassScore]) VALUES (3, 3072, 2007, CAST(83.099960 AS Decimal(38, 6)))
GO
INSERT [dbo].[ClassScore] ([Id], [StudentId], [SubjectId], [ClassScore]) VALUES (4, 3073, 2007, CAST(63.659980 AS Decimal(38, 6)))
GO
INSERT [dbo].[ClassScore] ([Id], [StudentId], [SubjectId], [ClassScore]) VALUES (5, 3071, 2008, CAST(88.428490 AS Decimal(38, 6)))
GO
INSERT [dbo].[ClassScore] ([Id], [StudentId], [SubjectId], [ClassScore]) VALUES (6, 3068, 2008, CAST(56.999970 AS Decimal(38, 6)))
GO
INSERT [dbo].[ClassScore] ([Id], [StudentId], [SubjectId], [ClassScore]) VALUES (7, 3072, 2008, CAST(79.571420 AS Decimal(38, 6)))
GO
INSERT [dbo].[ClassScore] ([Id], [StudentId], [SubjectId], [ClassScore]) VALUES (8, 3073, 2008, CAST(54.714200 AS Decimal(38, 6)))
GO
SET IDENTITY_INSERT [dbo].[ClassScore] OFF
GO

User's image

I want to get the position of each student per subject as below using SQL query

User's image

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

Answer accepted by question author

Erland Sommarskog 134.7K Reputation points MVP Volunteer Moderator
2023-08-27T09:46:30.27+00:00

Refer to the answer for your previous thread: https://learn.microsoft.com/en-us/answers/questions/1352595/order-records-based-on-value

You need to add a PARTITION BY clause to the OVER clause in that solution. Exactly how do to that is left as an excercise for the reader.

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.