具有联接且无重复的SQL联合

时间:2019-03-27 17:55:17

标签: sql sql-server

我有一个包含联接的SQL UNION,但我仍在重复,并且我不想重复。

这是我正在SQL Server中尝试的当前代码:

SELECT DISTINCT 
         e.[Id] AS [Id]
        ,e.[Body] AS [Description]
        ,e.[Subject] AS [Name]
        ,u.UserName AS [UserName]
        ,'email' AS [Type]
        ,e.[RecipientEmailAddress]
        ,e.[CreationTime]
        ,'email' AS [NoteTypeName]
        ,NULL AS [BackGroundClass]
        ,NULL AS [ColourClass]
FROM [dbo].[Emails] e
JOIN [dbo].[AbpUsers] u ON e.UserId = u.Id

UNION

SELECT DISTINCT 
     n.[Id] AS [Id]
    ,n.[Description]
    ,n.[Name]
    ,u.UserName AS [UserName]
    ,'note' AS [Type]
    ,NULL AS [RecipientEmailAddress]
    ,n.[CreationTime]
    ,pnt.[Name] AS [NoteTypeName]
    ,pnt.[BackGroundClass]
    ,pnt.[ColourClass]

FROM [dbo].[Notes] n
JOIN [dbo].[PicklistNoteTypes] pnt ON n.NoteTypeId = pnt.Id
JOIN [dbo].[AbpUsers] u ON n.UserId = u.Id
ORDER BY [Id]

预期结果是不包含重复项的结果集。

结果集:     enter image description here

0 个答案:

没有答案