我想根据某个条件从我的CTE中删除重复的条目,如果有2条记录具有相同的电子邮件地址,我希望只有具有refduserID的记录。应删除具有0 refdUserID的另一个重复记录。
答案 0 :(得分:1)
理论上,你可以添加第二个CTE和一个额外的列。此额外列根据特定条件为每一行分配一个行号 - 在您的情况下,按电子邮件地址分区(例如,在考虑“重复”行时要用于比较的列),以及任意顺序,以决定你要保留哪一个(我使用了referrerid,所以最早插入的将保留)。
然后在CTE的下一个“层”中,我只选择行号为1的那些 - 例如每个“小组”的顶部。
编辑:已更新实际代码,因为OP发布了它...
CREATE PROCEDURE [dbo].[Friendreferralsbyuser]
@userID INT
AS
WITH INV ( referrerID, refdEmail, referringTime, referredName, refdUserID )
AS (SELECT i.userID AS referrerID,
i.emailAddress AS refdEmail,
i.TIMESTAMP AS referringTime,
i.referredName,
0 AS refdUserID
FROM Invitations AS i
WHERE i.userID = @userID),
INR ( referrerID, refdEmail, joiningtime, referredName, refdUserID )
AS (SELECT i.referralID AS referrerID,
u.email AS refdEmail,
i.TIMESTAMP AS joiningtime,
u.userName AS referredName,
i.userID AS refdUserID
FROM InvitationReferrals AS i
INNER JOIN Users AS u
ON u.userID = i.userID
WHERE i.referralID = @userID),
JOINED ( referrerID, refdEmail, times, referredName, refdUserID )
AS (SELECT i.referrerID,
i.refdEmail,
i.referringTime,
i.referredName,
i.refdUserID
FROM INV AS i
UNION
SELECT i.referrerID,
i.refdEmail,
i.joiningtime,
i.referredName,
i.refdUserID
FROM INR AS i),
ROWNUMBERS (referrerID, refdEmail, times, referredName, refdUserID, RN)
AS (SELECT referrerID,
refdEmail,
times,
referredName,
refdUserID,
Row_number()
OVER (
PARTITION BY refdEmail
ORDER BY refdUserID DESC, referrerID))
SELECT referrerID,
refdEmail,
times,
referredName,
refdUserID
FROM ROWNUMBERS
WHERE RN = 1
答案 1 :(得分:1)
试试这个,
;With CTE as
(
select *, rank() over (partition by rfdEmail order by refduserID desc) as r
from myTable
)
delete from CTE where r > 1
答案 2 :(得分:1)
将此添加到我的存储过程中并且有效。
DuplicateSorting AS (
SELECT *,rank()OVER
(PARTITION BY refdEmail ORDER BY refduserID desc)AS nn FROM JOINED),
RemovedDuplicates AS ( 选择 * FROM DuplicateSorting 在哪里rn = 1 )
SELECT * FROM RemovedDuplicates