选择声明 - 仅在条件时

时间:2014-03-01 04:00:33

标签: sql-server sql

请查看下表:

Status ----------------- Email
Approved ----------------john@john.com 
Canceled --------------- john@john.com 
Canceled --------------- charles@charles.com 
Canceled --------------- charles@charles.com 
Canceled --------------- charles@charles.com 

我执行查询

"SELECT DISTINCT Status, Email FROM dbo.sales":

Status ----------------- Email
Approved --------------- john@john.com 
Canceled ----------------john@john.com 
Canceled --------------- charles@charles.com 

我想设置一个查询来选择状态为“已取消”的行只有当没有一行具有状态为“已批准”的相同电子邮件时。

换句话说,在这个例子中,我只会选择最后一个条目(Canceled - charles@charles.com)。

有可能吗?提前谢谢。

5 个答案:

答案 0 :(得分:1)

Select distinct status,email
From dbo.sales
Where email Not In ( select email from dbo.sales
                      Where status='Approved' )

答案 1 :(得分:0)

试试这个

Select  Status, Email
FROM dbo.sales
WHERE Status = 'Canceled' AND 
NOT EXIST(Select  Status, Email FROM dbo.sales Where Status='Approved')
GROUP BY Status, Email

答案 2 :(得分:0)

假设您只有'已批准'和'取消'作为状态列的值:

select status, email from dbo.sales
where email not in (select email from dbo.sales where status = 'Approved')
group by email

答案 3 :(得分:0)

您可以使用以下查询:

方法1:

SELECT DISTINCT t.status, t.email
FROM dbo.test t
LEFT JOIN (SELECT * FROM test WHERE STATUS = 'Approved')z ON z.email = t.email
WHERE t.STATUS = 'Canceled'
    AND z.STATUS IS NULL

方法2:

SELECT DISTINCT status, email
FROM dbo.sales t
WHERE t.STATUS = 'Canceled'
  and t.email Not In (  SELECT email 
                        FROM dbo.sales
                        WHERE status='Approved' )

答案 4 :(得分:0)

如果这只是关于取消的电子邮件,您可以尝试除以外:

SELECT Email FROM dbo.sales WHERE Status = 'Canceled'
EXCEPT
SELECT Email FROM dbo.sales WHERE Status = 'Approved'
;

或者,如果输出中必须包含Status

SELECT Status,     Email FROM dbo.sales WHERE Status = 'Canceled'
EXCEPT
SELECT 'Canceled', Email FROM dbo.sales WHERE Status = 'Approved'
;

如果你真的想要显示总是被批准或总是被取消的电子邮件,一种方法是为每个子集重复上述逻辑:

(
SELECT Status,     Email FROM dbo.sales WHERE Status = 'Canceled'
EXCEPT
SELECT 'Canceled', Email FROM dbo.sales WHERE Status = 'Approved'
)
UNION ALL
(
SELECT Status,     Email FROM dbo.sales WHERE Status = 'Approved'
EXCEPT
SELECT 'Approved', Email FROM dbo.sales WHERE Status = 'Canceled'
)
;

但是,您也可以尝试对组中不同的Status值进行分组和计数:

SELECT
  MIN(Status) AS Status,
  Email
FROM
  dbo.sales
GROUP BY
  Email
HAVING
  COUNT(DISTINCT Status) = 1
;

这种其他方法适用于任意数量的Status es。