我有一个表格,列名为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
现在我想要的是所有流程 - Process1,process2,流程3的状态已关闭的人员的emailId和状态
**Output**
EmailId Status
orange@fruits.com Closed
由于橙色的所有过程都已关闭,我有上面的行 同样,我希望获得表格的所有电子邮件ID,其过程已关闭。
答案 0 :(得分: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)
答案 1 :(得分: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 ;