在case语句中不是单组函数

时间:2015-12-15 12:18:49

标签: sql oracle

tab1
ID_P , SYN
 1      0
 2      0
 2      1
 2      0

tab2
ID_P , SYN
 2      1
 2      1
 4      0

select CASE WHEN COUNT(SYN) > 1 THEN '0' 
            WHEN COUNT(SYN) = 0 AND SYN > 0 THEN '0' 
            ELSE '1' END 
from (
select COUNT(SYN) as SYN
from tab1
where ID_P = 2 and SYN <> '0' 
union
select COUNT(SYN) as SYN
from tab2
where ID_P = 2 and SYN <> '0' ) 

我要验证的是

  1. 如果来自联盟的返回结果有多行,则返回'0'
  2. 如果来自联合的返回结果只包含一行而且唯一的结果是大于零然后返回'0'
  3. 问题发生在第二个语句中, ORA-00937不是单组组功能,我怎样才能克服这个问题? 结果应该为零,因为有些行包含'1'。 提前致谢 最好的问候

1 个答案:

答案 0 :(得分:0)

  

实际上我对你想要实现的目标感到困惑,   以下示例可能会帮助您

  SELECT
  CASE
    WHEN COUNT(1) > 1
    THEN '0'
    WHEN COUNT(1) =1
    AND MAX(A.SYN)     > 0
    THEN '0'
    ELSE '1'
  END col1
FROM
  (SELECT COUNT(SYN) AS SYN
  FROM
    (SELECT 1 ID_P,0 SYN FROM DUAL
    UNION ALL
    SELECT 2 ID_P,0 SYN FROM DUAL
    UNION ALL
    SELECT 2 ID_P,1 SYN FROM DUAL
    UNION ALL
    SELECT 2 ID_P,0 SYN FROM DUAL
    )
  WHERE ID_P = 2
  AND SYN   <> '0'
  UNION
  SELECT COUNT(SYN) AS SYN
  FROM
    (SELECT 2 ID_P,1 SYN FROM DUAL
    UNION ALL
    SELECT 2 ID_P,1 SYN FROM DUAL
    UNION ALL
    SELECT 4 ID_P,0 SYN FROM DUAL
    )
  WHERE ID_P = 2
  AND SYN   <> '0'
  ) a;