我有一个SQL表,包括id,name,email,....我有另一个有id,email,emailstatus的SQL表,但是这两个id不同,它们没有关系。这两个表之间唯一常见的是电子邮件。
我想加入这两个表,带来table1中的所有信息,如果表1和表2中的电子邮件地址相同,则emailstatus为'Bounced'。但是我写的查询给了我比我预期更多的记录,因为申请人(第一张表)中每行的tbl_webhook(第二个表)中有多行。我想知道申请人是否曾经有过电子邮件反弹。
没有连接的查询显示23000条记录但是在加入后显示42000条记录是因为重复我怎么能保持相同的23000条记录只能从第二张表中添加信息?
这是我的疑问:
SELECT
A.[Id]
,A.[Application]
,A.[Loan]
,A.[Firstname]
,A.[Lastname]
,A.[Email],
,H.[Email], H.[EmailStatus] as BouncedEmail
FROM Applicant A (NOLOCK)
left outer join [tbl_Webhook] [H] (NOLOCK)
on A.Email = H.Email
and H.[event]='bounced'
这是所需数据的样本:
id email name emailFromTable2 emailstatus
1 test2@yahoo.com lili test2@yahoo.com bounced
2 tesere@yahoo.com mike Null Null
3 tedfd2@yahoo.com nik tedfd2@yahoo.com bounced
4 tdfdft2@yahoo.com sam Null Null
5 tedft2@yahoo.com james tedft2@yahoo.com bounced
6 tedft2@yahoo.com San Null
答案 0 :(得分:1)
对此类查询使用嵌套select
。我会把它写成:
select id, application, load, firstname, lastname, email,
(case when BouncedEmail is not null then email end) as EmailFromTable2,
BouncedEmail
from (SELECT A.[Id], A.[Application], A.[Loan], A.[Firstname], A.[Lastname], A.[Email],
(case when exists (select 1
from tbl_WebHook h
where A.Email = H.Email and H.[event] = 'bounced'
)
then 'bounced
end) as BouncedEmail
FROM Applicant A (NOLOCK)
) a
您也可以使用cross apply
执行此操作,但由于您只需要一列,因此相关子查询也可以正常工作。
答案 1 :(得分:1)
;WITH DistinctEmails
AS
(
SELECT * , rn = ROW_NUMBER() OVER (PARTITION BY [Email] ORDER BY [Email])
FROM [tbl_Webhook]
)
SELECT
A.[Id]
,A.[Application]
,A.[Loan]
,A.[Firstname]
,A.[Lastname]
,A.[Email],
,H.[Email], H.[EmailStatus] as BouncedEmail
FROM Applicant A (NOLOCK) left outer join DistinctEmails [H] (NOLOCK)
on A.Email = H.Email
WHERE H.rn = 1
and H.[event]='bounced'
答案 2 :(得分:1)
我相信下面的查询应该足以为您选择不同的退回电子邮件,欢呼:)
SELECT
A.[Id]
,A.[Application]
,A.[Loan]
,A.[Firstname]
,A.[Lastname]
,A.[Email],
,H.[Email], H.[EmailStatus] as BouncedEmail
FROM Applicant A (NOLOCK)
Inner join [tbl_Webhook] [H] (NOLOCK)
on A.Email = H.Email
and H.[EmailStatus]='bounced'
基本上我只是将连接更改为内部连接并将第二个表条件从事件更改为emailstatus,如果您可以提供表结构和示例数据,我相信我可以帮助您:)