SQL如何将CASE与NOT EXISTS语句一起使用

时间:2013-07-19 12:10:04

标签: sql-server exists

我在SQL中有一个非常复杂的查询,我从各种表中提取大量信息并进行各种连接。我想拉一个列来检查特定的tradeId是否包含在2个不同的表中。尽管如此,我仍然不知道如何正确地做到这一点。

以下代码为我提供了Trade表中所有不在TCM中的TradeIds(它只是2个表的组合)。但是,我希望所有交易来自交易表,然后是一列,以表明它是否在TCM中找到。

我知道这可以通过CASE WHEN查询完成,但我很困惑如何构建它以便它适合CASE WHEN。

With subCA As
(Select distinct OTPTradeId, ConfoAuditSenderRef from ConfirmationAudit where ConfoAuditSenderRef like 'HBEUM%'),
TCM As
(Select distinct OTPTradeID from subCA union ALL select TradeId from subCA inner join ConfirmationSent on (OTPTradeId = ConfoId 
AND ConfoAuditSenderRef like 'HBEUMN%'))
select TradeId from Trade where NOT EXISTS (Select OtpTradeId from TCM where OtpTradeId = TradeId) 
and TradeDate = '17 jun 2013'

继承我尝试将其放入CASE WHEN语句但是我收到错误,因为如果没有我认为的WHERE,则不允许使用NOT EXISTS。但我所追求的是这样的。如果我使用NOT IN它变得非常缓慢,就像5分钟一样,这是一个更大的查询的一部分,我不希望它花这么长时间 - 如果可能的话!

With subCA As
(Select distinct OTPTradeId, ConfoAuditSenderRef from ConfirmationAudit where ConfoAuditSenderRef like 'HBEUM%'),
TCM As
(Select distinct OTPTradeID from subCA union ALL select TradeId from subCA inner join ConfirmationSent on (OTPTradeId = ConfoId 
AND ConfoAuditSenderRef like 'HBEUMN%'))
select TradeId,
CASE WHEN
    (TradeId NOT EXISTS (Select OtpTradeId from TCM where OtpTradeId = TradeId) Then 'Y' Else 'N' End As 'TCM' 
from Trade
WHERE TradeDate = '17 jun 2013'

3 个答案:

答案 0 :(得分:9)

试试这个 -

SELECT
       t.TradeId
     , CASE WHEN NOT EXISTS (
          SELECT 1
          FROM TCM t2
          WHERE t2.OtpTradeId = t.TradeId
      ) Then 'Y' Else 'N' END As 'TCM' 
FROM Trade t
WHERE t.TradeDate = '17 jun 2013'

答案 1 :(得分:3)

更改部分

TradeId NOT EXISTS

TradeId NOT IN

查看EXISTS (Transact-SQL)IN (Transact-SQL)

之间的区别

看看这个小例子

SQL Fiddle DEMO

除此之外,可能会重新审视CASE (Transact-SQL)

的语法
Simple CASE expression: 
CASE input_expression 
     WHEN when_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END 
Searched CASE expression:
CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

答案 2 :(得分:0)

你可以使用  NOT IN。根据您的需要尝试。