我有两个桌子。我有一个通过INNER JOIN
子句将第一个表连接到第二个表的查询。结果表明存在冗余或重复的结果。在下面的示例中,结果有4条记录。我想区分SdiID
,由于sdiID
只有两个唯一的记录,因此我希望只得到两个记录。我尝试在选择之后添加DISTINCT sdiID
,但仍然得到4条记录。请帮忙。这是我的查询。
DECLARE @PageNumber AS INT, @RowspPage AS INT
SET @PageNumber = 1
SET @RowspPage = 20
SELECT totalCount = COUNT(*) OVER(), mailbox.ID as mailboxID,
sdi.ID as sdiID
FROM [SDI].dbo.UserDocumentLocationOutbox mailbox
INNER JOIN [SDI].dbo.SDITransaction
sdi on mailbox.SDITransactionID=sdi.ID
INNER JOIN [SYSDB].dbo.DocumentType doc on sdi.DocumentTypeID=doc.ID
where mailbox.CommunityID = '9ff10c7a-37f5-4580-9163-6ada55194ca7'
and mailbox.UserProfileID = 'f9791614-8cc0-42e3-87d1-53709bc1e099'
and doc.CommunityID = '9ff10c7a-37f5-4580-9163-6ada55194ca7'
and doc.Active=1 and doc.HideInMailbox=0
order by sdi.ProcessedDateTime desc
OFFSET ((@PageNumber - 1) * @RowspPage) ROWS FETCH NEXT @RowspPage ROWS ONLY
这是结果
答案 0 :(得分:1)
with cte as (SELECT ROW_NUMBER() over(PARTITION BY sdi.ID order by sdi.ID) as rn,totalCount = COUNT(*) OVER(), mailbox.ID as mailboxID,
sdi.ID as sdiID
FROM [SDI].dbo.UserDocumentLocationOutbox mailbox
INNER JOIN [SDI].dbo.SDITransaction
sdi on mailbox.SDITransactionID=sdi.ID
INNER JOIN [SYSDB].dbo.DocumentType doc on sdi.DocumentTypeID=doc.ID
where mailbox.CommunityID = '9ff10c7a-37f5-4580-9163-6ada55194ca7'
and mailbox.UserProfileID = 'f9791614-8cc0-42e3-87d1-53709bc1e099'
and doc.CommunityID = '9ff10c7a-37f5-4580-9163-6ada55194ca7'
and doc.Active=1 and doc.HideInMailbox=0
order by sdi.ProcessedDateTime desc
OFFSET ((@PageNumber - 1) * @RowspPage) ROWS FETCH NEXT @RowspPage ROWS ONLY)
select totalCount, mailboxID, sdiID
from cte
where rn < 2
答案 1 :(得分:0)
由于您有4个不同的mailboxID值,因此您将始终获得4个查询结果。即,您的每个sdiID都有两个关联的MailboxID,因此它们是不同的记录。您可以通过选择MAX(mailbox.id)作为mailboxID或MIN(Mailbox.id)作为mailboxID并按ID分组来删除每个ID中的一个。