1

我有一个表,其中包含 Name、EmailId、Process、Status 列,如下所示。

**Input**

   Name       EmailId                Process      Status    
   apple1     apple@fruits.com       process1     Closed
   apple2     apple@fruits.com       process2     In Progress
   apple3     apple@fruits.com       process3     Complete      
   orange1    orange@fruits.com      process1     Closed
   orange2    orange@fruits.com      process2     Closed
   oran       orange@fruits.com      process3     Closed
   mango1     mango@fruits.com       process1     To Start

现在我想要的是所有进程的状态都关闭的人的 emailId 和状态 - Process1,process2,process 3

**Output**

EmailId              Status    
orange@fruits.com    Closed

由于橙色的所有进程都已关闭,因此我有上面的行类似地,我希望拥有进程已关闭的表的所有电子邮件 ID。

4

2 回答 2

3

要找到这一点,您可以使用聚合COUNT()来查找HAVING子句中的 count = 3,因此所有三个都是关闭的:

SELECT
  EmailId,
  /* How many different processes are closed per EmailId */
  COUNT(DISTINCT Process) AS numclosed
FROM
  yourtable
WHERE Status = 'Closed'
GROUP BY EmailId
/* Return only those with 3 processes closed */
HAVING numclosed = 3

如果可能的进程数不完全是 3 并且您需要考虑所有这些,我相信您可以在HAVING子句中使用子查询来查找可能的进程的实际数量

SELECT
  EmailId,
  COUNT(DISTINCT Process) AS numclosed
FROM
  yourtable
WHERE Status = 'Closed'
GROUP BY EmailId
/* Compare the number closed for this EmailId against the number of possible Process values in the table */
HAVING numclosed = (SELECT COUNT(DISTINCT Process) FROM yourtable)
于 2012-07-12T12:19:57.450 回答
2

其他方式:

SELECT 
    EmailId
FROM
    tableX AS t
GROUP BY 
    EmailId
HAVING
    COUNT( CASE WHEN Status <> 'Closed'
             THEN 1 
           END
         ) = 0 ;

或者:

SELECT 
    t.EmailId
FROM
    ( SELECT DISTINCT EmailId
      FROM tableX 
    ) AS t
  LEFT JOIN
    tableX AS tt
      ON  tt.EmailId = t.EmailId
      AND tt.Status <> 'Closed'
WHERE
    tt.EmailId IS NULL ;
于 2012-07-12T12:40:15.293 回答