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

问题描述 投票:0回答:1

这是用于创建表和一些数据的脚本。

--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语句那样使用ConcatTo = 1的“ Lily2 Michilin2 Joshua2”更新StudentName列?然后删除Lily2和Joshua2行?

sql-server sql-update partition redundancy for-xml-path
1个回答
0
投票

您可以使用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删除为空

DELETE  s
FROM    Students s
WHERE   s.ConcatTo  IS NULL
© www.soinside.com 2019 - 2024. All rights reserved.