我有一个带有列的表:唯一ID,收件人,发送日期和状态。
当send_date> xx并且status ='something'时,我想为不同的收件人选择ID
我已经尝试过了:
SELECT *
FROM EmailMessage
WHERE Recipients in
(SELECT Recipients
FROM EmailMessage
GROUP BY Recipients
HAVING COUNT(Recipients)=1)
and sent_date > '2018-12-31 23:59:59'
and status = 'failed'
但这产生的结果太少,似乎有些不正确。我正在使用SQL Server MS。
答案 0 :(得分:1)
当send_date> xx时,我想为不同的收件人选择ID 和状态=“某物”
这在sql中是这样翻译的:
SELECT DISTINCT Recipients
FROM EmailMessage
WHERE
sent_date > '2018-12-31 23:59:59'
AND
status = 'failed'
或
SELECT Recipients
FROM EmailMessage
WHERE
sent_date > '2018-12-31 23:59:59'
AND
status = 'failed'
GROUP BY Recipients
答案 1 :(得分:0)
这将返回失败和日期条件为真的行:
SELECT em.*
FROM EmailMessage
WHERE sent_date >= '2019-01-01' AND status = 'failed';
我不确定“不同的收件人”是什么意思。但是您可以使用窗口函数(或其他方法)为每个收件人获得一行:
SELECT em.*
FROM (SELECT em.*,
ROW_NUMBER() OVER (PARTITION BY recipient ORDER BY sent_date) as seqnum
FROM EmailMessage
WHERE sent_date >= '2019-01-01' AND status = 'failed'
) em
WHERE seqnum = 1;