我需要按UniqueIdentifier
列进行分组,该表还包含XML列。如何按列分组 - SQL Server
表模式:StudentMark:
CREATE TABLE [dbo].[StudentMark]
(
[StudentMarkId] [int] IDENTITY(1,1) NOT NULL,
[StudentId] [uniqueidentifier] NULL,
[SubjectId] [uniqueidentifier] NULL,
[ScoreInfo] [xml] NULL,
[GeneratedOn] [datetime2](2) NOT NULL,
CONSTRAINT [PK_StudentMark]
PRIMARY KEY CLUSTERED ([StudentMarkId] ASC)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
样品种子数据
INSERT INTO [dbo].[StudentMark] ([StudentId], [SubjectId], [ScoreInfo], GeneratedOn])
VALUES ('FC3CB475-B480-4129-9190-6DE880E2D581', '0D72F79E-FB48-4D3E-9906-B78A9D105081', '<StudentMarkAttribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></StudentMarkAttribute>', '2017-08-10 10:20:15'),
('0F4EF48C-93E3-41AA-8295-F6B0E8D8C3A2', '0D72F79E-FB48-4D3E-9906-B78A9D105081', '<StudentMarkAttribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></StudentMarkAttribute>', '2017-08-10 10:20:15'),
('0F4EF48C-93E3-41AA-8295-F6B0E8D8C3A2', 'AB172272-D2E9-49E1-8040-6117BB6743DB', '<StudentMarkAttribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></StudentMarkAttribute>', '2017-08-16 09:06:20'),
('FC3CB475-B480-4129-9190-6DE880E2D581', 'AB172272-D2E9-49E1-8040-6117BB6743DB', '<StudentMarkAttribute xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"></StudentMarkAttribute>', '2017-08-16 09:06:20');
要求:我需要按[dbo].[StudentMark].[StudentId]
采取的最新记录。
我尝试以下SQL查询,但它造成的错误
SELECT
MAX([StudentMarkId]), [StudentId], [SubjectId], [ScoreInfo], [GeneratedOn]
FROM
[dbo].[StudentMark]
GROUP BY
[StudentId]
错误:
列“dbo.StudentMark.SubjectId”是因为它是在选择列表中无效不包含在聚合函数或GROUP BY子句中。
我审阅了以下问题,但我不能修复:Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause
请帮助我。
SELECT *
FROM (
SELECT *,
ROW_NUMBER() OVER(PARTITION BY StudentId ORDER BY StudentMarkId DESC) AS rn
FROM [dbo].[StudentMark]) sub
WHERE sub.rn = 1;
请您确认一下,我们不能使用“分组依据”?而不是'Row_Number'方法? –
@ B.Balamanigandan您不能以您建议的方式使用GROUP BY。你的问题很清楚,“每组最大的第n个” – lad2025
你能否确认哪一个答案更可取?在优化方面的两个答案? –