简体   繁体   English

使用where子句为不同的值选择id

[英]Select ids for distinct value with where clause

I have a table with columns: unique id, recipients, sent_date and status. 我有一个带有列的表:唯一ID,收件人,sent_date和状态。

I would like select ids for distinct recipients when sent_date > xx and status = 'something' 当send_date> xx并且status ='something'时,我想为不同的收件人选择id

I have tried this: 我已经试过了:

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'

But this produces too few results and something seems not right. 但这产生的结果太少,似乎有些不正确。 I am using SQL Server MS. 我正在使用SQL Server MS。

I would like select ids for distinct recipients when sent_date > xx and status = 'something' 当send_date> xx并且status ='something'时,我想为不同的收件人选择id

This translated in sql is this: sql的翻译是这样的:

SELECT DISTINCT Recipients  
FROM EmailMessage 
WHERE 
  sent_date > '2018-12-31 23:59:59'
  AND 
  status = 'failed'

or 要么

SELECT Recipients  
FROM EmailMessage 
WHERE 
  sent_date > '2018-12-31 23:59:59'
  AND 
  status = 'failed'
GROUP BY Recipients

This returns rows where the failure and date conditions are true: 这将返回失败和日期条件为true的行:

SELECT em.*
FROM EmailMessage 
WHERE sent_date >= '2019-01-01' AND status = 'failed';

I'm not sure what "distinct recipient" means. 我不确定“不同的收件人”是什么意思。 But you can get one row per recipient using window functions (or some other method): 但是您可以使用窗口函数(或其他方法)为每个收件人获得一行:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM