特定列需要区分的内部联接

时间:2016-01-05 19:10:53

标签: sql-server

我正在编写以下存储过程:

SELECT invite.sender_id,
       invite.invite_msg_text,
       invite.date_sent,
       person.name_first,
       person.name_last,
       member.member_image_url
FROM   invite
       INNER JOIN person
               ON invite.sender_id = person.person_id
       INNER JOIN member
               ON invite.sender_id = member.person_id
WHERE  invite.invite_status = 'P'
       AND invite.recipient_email = @recipientEmail
ORDER  BY invite.date_sent DESC 

但我想返回具有不同sender_id / person_id的行。现在,如果用户发送了多个邀请,它将返回重复的行。是否可以仅基于sender_id / person_id

返回不同的行

2 个答案:

答案 0 :(得分:1)

这应该为您提供sender_id发送的最新邀请。使用row_number确定最后发送的邀请。

SELECT * FROM 
(
    SELECT invite.sender_id,
           invite.invite_msg_text,
           invite.date_sent,
           person.name_first,
           person.name_last,
           member.member_image_url,
           ROW_NUMBER() OVER (PARTITION BY invite.sender_id ORDER BY invite.date_sent DESC) Rn 
    FROM   invite
           INNER JOIN person
                   ON invite.sender_id = person.person_id
           INNER JOIN member
                   ON invite.sender_id = member.person_id
    WHERE  invite.invite_status = 'P'
           AND invite.recipient_email = @recipientEmail
) t
WHERE t.RN = 1
ORDER BY t.date_sent DESC 

答案 1 :(得分:0)

SELECT invite.sender_id, invite.invite_msg_text, invite.date_sent, person_a.name_first, person_a.name_last, member.member_image_url
FROM invite
INNER JOIN (select person_id, max(name_first) as name_first,max(name_last) as name_last from person group by person_id) as person_a 
ON person_a.person_id = invite.sender_id

应该完成你的目标。