将列值附加到重复记录中的某些记录并删除重复记录

Append column values to certain records from duplicated records and remove duplicated records

这是创建 table 和一些数据的脚本。

--Students table ---------
CREATE TABLE [Students](
    [ID] [int] NOT NULL,
    [SubjectID] [int] NULL,
    [StudentName] [nvarchar](50) NULL,
    [ConcatTo] [bit] NULL
) ON [PRIMARY]
GO
INSERT [Students] ([ID], [SubjectID], [StudentName], [ConcatTo]) VALUES (1, 1, N'Mary', 1)
GO
INSERT [Students] ([ID], [SubjectID], [StudentName], [ConcatTo]) VALUES (2, 1, N'Brown', NULL)
GO
INSERT [Students] ([ID], [SubjectID], [StudentName], [ConcatTo]) VALUES (3, 2, N'Lily2', NULL)
GO
INSERT [Students] ([ID], [SubjectID], [StudentName], [ConcatTo]) VALUES (4, 2, N'Michilin2', 1)
GO
INSERT [Students] ([ID], [SubjectID], [StudentName], [ConcatTo]) VALUES (5, 2, N'Joshua2', NULL)
GO


select *from Students;

SELECT Main.SubjectID, main.Students As "Students" 
FROM
(
    SELECT DISTINCT t2.SubjectID, 
        (
            SELECT t1.StudentName + ' ' AS [text()]
            FROM dbo.Students t1
            WHERE t1.SubjectID = t2.SubjectID
            FOR XML PATH ('')
        ) Students
    FROM dbo.Students t2
) Main

Select从table会有这个

最多我只知道 select 这样,但我不知道如何更新我的学生 table 这样

这是我对预期结果的截图。

如何使用 "Lily2 Michilin2 Joshua2" 更新 StudentName 列,其中 ConcatTo = 1 就像我的 select 语句一样?然后删除 Lily2 和 Joshua2 行?

您可以使用 CTE 包装您现有的查询,然后使用它连接回您的原始查询并更新它

WITH CTE AS
(
    SELECT ID, Main.SubjectID, Main.Students As Students
    FROM
    (
        SELECT ID = MIN(CASE WHEN t2.ConcatTo IS NOT NULL THEN t2.ID END), t2.SubjectID, 
        (
            SELECT t1.StudentName + ' ' AS [text()]
            FROM  Students t1
            WHERE t1.SubjectID = t2.SubjectID
            FOR XML PATH ('')
        ) Students
        FROM  Students t2
        GROUP BY t2.SubjectID
    ) Main
)
UPDATE  s
SET     StudentName = c.Students
FROM    Students s
        inner join CTE c    ON  s.ID    = c.ID 

对于第二部分,只需删除 ConcatTo is null

DELETE  s
FROM    Students s
WHERE   s.ConcatTo  IS NULL