如何按列分组 - SQL Server

时间:2017-08-17 10:03:15

标签: sql sql-server xml group-by sql-server-2016

我需要按UniqueIdentifier列进行分组,该表还包含XML列。

表架构: 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

请帮助我。

3 个答案:

答案 0 :(得分:3)

使用'Authorization': 'Basic ' + btoa(username + ':' + password) 计算群组内的位置:

ROW_NUMBER

答案 1 :(得分:1)

如果您有Students表格,则替代解决方案效果最佳:

select sm.*
from students s cross apply
     (select top 1 sm.*
      from studentmark sm
      where sm.studentid = s.studentid
      order by sm.generatedon desc
     ) sm;

答案 2 :(得分:0)

您不能按XMLTEXT列进行分组,首先需要转换为varchar(max)

SELECT 
    MAX([StudentMarkId]), [StudentId], [SubjectId],
    CONVERT(XML, CONVERT(VARCHAR(MAX), [ScoreInfo])) DetailXML,
    [GeneratedOn]
FROM 
    [dbo].[StudentMark] 
GROUP BY 
    [StudentId], [SubjectId], 
    CONVERT(VARCHAR(MAX), [ScoreInfo]), [GeneratedOn]

在第一行,它被转换为varchar(max)以匹配GROUP BY子句,稍后它将重新转换回XML。