select Y if column if count(colmn1) with value A and B is 0 using aggregate funtion

select Y if column if difference of count(colmn1) with value A and B is 0 using aggregate funtion

我有一个 table,名称为 table COM24 如果 movetype='C'movetype='D' 匹配,我必须 select Y,反之亦然 COM24 poliref,inrctyp,inrcref,csntype,duedate,itrno.

我正在尝试做的是如下所示。 我正在尝试解释我需要的逻辑,我知道下面会有错误

SELECT 'Y'
FROM  COM24  c2
HAVING  ( (COUNT(c2.movetype) = 'C')  - (COUNT(c2.movetype='D') ) ) =0  
AND c2.csnstat!= 90
GROUP BY  c2.poliref , c2.inrctyp , c2.inrcref , c2.csntype , c2.duedate , c2.itrno

所以基本上要求是 if "count of movetyp with value 'C'" - "count of movetype with value 'D'" for the same poliref,inrctyp,inrcref,csntype,duedate,itrno 为 0 那么 return Y

用sum就可以得到结果,还有很多其他方法可以做到。

SELECT CASE
           WHEN SUM(CASE
                        WHEN c2.movetype = 'C' THEN
                         1
                        WHEN c2.movetype = 'D' THEN
                         -1
                        ELSE
                         0
                    END) = 0 THEN
            'Y'
           ELSE
            'N'
       END
  FROM com24 c2
 WHERE c2.csnstat != 90
 GROUP BY c2.poliref,
          c2.inrctyp,
          c2.inrcref,
          c2.csntype,
          c2.duedate,
          c2.itrno

更新: 如果你想要游标中的值,你可以这样写代码

CURSOR C1 AS
WITH t_table AS (
    SELECT c2.poliref,
           c2.inrctyp,
           c2.inrcref,
           c2.csntype,
           c2.duedate,
           c2.itrno,
           CASE
               WHEN SUM(CASE
                        WHEN c2.movetype = 'C' THEN
                         1
                        WHEN c2.movetype = 'D' THEN
                         -1
                        ELSE
                         0
                    END) = 0 THEN
            'Y'
           ELSE
            'N'
           END AS flag
      FROM com24 c2
     WHERE c2.csnstat != 90
     GROUP BY c2.poliref,
              c2.inrctyp,
              c2.inrcref,
              c2.csntype,
              c2.duedate,
              c2.itrno)
SELECT *
  FROM t_table       
 WHERE flag = 'Y';

You requirement may be a little different but you can get some idea from the answers on how to write your code.

您提到过您正在使用光标。我会做这样的事情(尚未测试)-

DECLARE
 cursor c1 is 
   select c2.poliref, c2.inrctyp, c2.inrcref, c2.csntype, c2.duedate, c2.itrno
   from com24 c2
   where c2.csnstat != 90
   and c2.movetype = 'C'
   minus
   select c2.poliref, c2.inrctyp, c2.inrcref, c2.csntype, c2.duedate, c2.itrno
   from com24 c2
   where c2.csnstat != 90
   and c2.movetype = 'D';

BEGIN
  open c1;
  fetch c1;
  if c1%notfound then
    /* Handle 'Y' return.. e.g: */
    dbms_output.put_line('Y');
  end if;
END;
/

让我知道这是否正是您正在寻找的。