我正在编写一个查询,该查询应该向一组用户显示,他/她收到了哪些电子邮件以及该电子邮件是否打开。
这是查询的结果:
Product | Year | Month | SendTime | UserId | EmailTitle | Open
That one | 2018 | 11 | 2018-11-23 | 1000756 | JoinUs | 1
That one | 2018 | 11 | 2018-11-25 | 1000756 | JoinUs | 0
That one | 2019 | 1 | 2019-01-04 | 1000756 | Need Help? | 0
That one | 2019 | 4 | 2019-04-07 | 1000756 | Win Back | 0
That one | 2019 | 4 | 2019-04-10 | 1000756 | A gift to you | 0
我的问题是,用户每月可以多次收到同一封电子邮件,并且只打开其中一封。一个例子是JoinUs EmailTitle,它在第23和25天收到,但只有23封邮件是打开的。
因此,在这种情况下,当我发送两封相等的电子邮件时,我只需要显示一行,而我只需要显示打开的那一行即可。
SELECT S.Product,
YEAR(S.SendTime) [Year],
MONTH(S.SendTime) [Month],
S.SendTime SendTime,
S.UserId,
M.EmailName,
CASE WHEN Mo.ContactID IS NOT NULL THEN 1 ELSE 0 END [Open]
FROM MailSend S
JOIN CommMapping2 M on M.EmailName = S.EmailName
LEFT JOIN MailOpen Mo ON Mo.JobId = S.JobId AND Mo.BatchID = S.BatchID AND Mo.ContactID = S.ContactID
WHERE S.UserId IS NOT NULL AND S.UserId = '1000756'
答案 0 :(得分:1)
您可以使用rownumber
和partition
和userid
制作EmailTitle
。这样,在收到两封电子邮件的情况下,您只会收到一封打开的电子邮件。
with cte as (
SELECT S.Product,
YEAR(S.SendTime) [Year],
MONTH(S.SendTime) [Month],
S.SendTime SendTime,
S.UserId,
M.EmailName,
CASE WHEN Mo.ContactID IS NOT NULL THEN 1 ELSE 0 END [Open],
ROW_NUMBER() over (partition by UserId, EmailTitle order by CASE WHEN Mo.ContactID IS NOT NULL THEN 1 ELSE 0 END desc) as number
FROM MailSend S
JOIN CommMapping2 M on M.EmailName = S.EmailName
LEFT JOIN MailOpen Mo ON Mo.JobId = S.JobId AND Mo.BatchID = S.BatchID AND Mo.ContactID = S.ContactID
WHERE S.UserId IS NOT NULL AND S.UserId = '1000756'
)
select *
from cte
where number = 1