用于查看多个条件的SQL,如果ANY无效,则提供单个“NotOk”值

时间:2018-04-27 14:34:49

标签: sql sql-server

SQL Geeks的问题。

如果以下3个条件中的任何一个返回“N”值,我正试图在表格上设置一个标志。基本上,如果满足3个条件中的任何一个,那么我需要在Control表上设置一个标志。我无法弄清楚如何做到这一点,因为我还想返回一个原因,控制表将设置为'N'。这种方法在一个条件下工作正常但有3个我不确定。

这是SQL:

select Reason, TheCount,Dating_OK_to_Proceed 
from
(
SELECT  'More than 2 Seasons Are Open' as Reason,  COUNT(SEASCLOSED) as TheCount, 
case when COUNT(SEASCLOSED) > 2 then 'N' else 'Y' END as Dating_OK_to_Proceed
FROM dbo.DATING
GROUP BY SEASCLOSED
HAVING (SEASCLOSED = 0)

union all

SELECT  'More than 1 Season has Ordering Switched On'  as Reason,  
COUNT(ORDERON) as TheCount,
case when COUNT(ORDERON) > 1 then 'N' else 'Y' END as Dating_OK_to_Proceed
FROM dbo.DATING
GROUP BY seasclosed, ORDERON
HAVING (ORDERON > 0) and SEASCLOSED = 0

union all

SELECT  'More than 1 Season has Invoicing Switched On'  as Reason,  
COUNT(INVOICEON) as TheCount,
case when COUNT(INVOICEON) > 1 then 'N' else 'Y' END as Dating_OK_to_Proceed
FROM dbo.DATING
GROUP BY seasclosed, INVOICEON
HAVING (INVOICEON > 0) and SEASCLOSED = 0
) as OkGo

如果所有3个条件都返回Y而不是3行,我想返回一行“Y”。

但是如果任何条件返回'N',那么我想返回一个具有相应原因和'N'的行。

这可能吗?

1 个答案:

答案 0 :(得分:0)

解决此问题的一种方法:

with OkGo as
 (
    SELECT  'More than 2 Seasons Are Open' as Reason,  COUNT(SEASCLOSED) as TheCount, 
    case when COUNT(SEASCLOSED) > 2 then 'N' else 'Y' END as Dating_OK_to_Proceed
    FROM dbo.DATING
    GROUP BY SEASCLOSED
    HAVING (SEASCLOSED = 0)

    union all

    SELECT  'More than 1 Season has Ordering Switched On'  as Reason,  
    COUNT(ORDERON) as TheCount,
    case when COUNT(ORDERON) > 1 then 'N' else 'Y' END as Dating_OK_to_Proceed
    FROM dbo.DATING
    GROUP BY seasclosed, ORDERON
    HAVING (ORDERON > 0) and SEASCLOSED = 0

    union all

    SELECT  'More than 1 Season has Invoicing Switched On'  as Reason,  
    COUNT(INVOICEON) as TheCount,
    case when COUNT(INVOICEON) > 1 then 'N' else 'Y' END as Dating_OK_to_Proceed
    FROM dbo.DATING
    GROUP BY seasclosed, INVOICEON
    HAVING (INVOICEON > 0) and SEASCLOSED = 0
 ) 
, RankedReasons as
 ( select Reason, TheCount, Dating_OK_to_Proceed,
      -- if there's any 'N' it will be sorted first and gets rank 1,
      -- otherwise 1 is assigned to the first 'Y'
      row_number()
      over (order by Dating_OK_to_Proceed) as rnk
   from OkGo
 )
select * from RankedReasons
where rnk = 1 --return a single row for 'Y' or one out of multiple 'N's 

要使用'N'获取所有行,您只需添加最终

   or Dating_OK_to_Proceed = 'N'