获得计数

时间:2013-03-14 12:59:14

标签: sql sql-server

我是SQL的新手,并且已经坚持使用这段代码几天了。

select distinct Count( AGVGLST.AGVGLST_PIDM ) "Count_AGVGLST_PIDM",
       Count( (select distinct pidm
       from donor
       where donor.pidm = agvglst_pidm
       and donor.cfae_cat IN ('ALMB','ALMX')) ) "Cfae"
  from AGVGLST
 where AGVGLST.AGVGLST_DESG ='1125'
       and AGVGLST.AGVGLST_FISC_CODE ='2010'
       and not exists(select 'x'
       from agvglst b
       where b.agvglst_pidm = agvglst_pidm
       and b.agvglst_desg <> '1125'
       and b.agvglst_fisc_code = '2010')

我试图只计算这个“1125”的分数,所以我需要引用它两次,出于某种原因,当我知道捐赠者只捐赠给那个特定的分配时,我得到零计数。我确信这是我想念的蠢事。

3 个答案:

答案 0 :(得分:1)

   not exists(select 'x'
   from agvglst b
   where b.agvglst_pidm = agvglst_pidm
   and b.agvglst_desg <> '1125'
   and b.agvglst_fisc_code = '2010')

可能这是在这里造成问题。可能有捐赠者的名称不是'1125'但agvglst_fisc_code是'2010'。因此,由于存在记录,您的不存在会限制“1125”被计算在内。

答案 1 :(得分:0)

当一些应该简单的东西开始过于复杂化时;是时候备份并重新开始了:

select 
  AGVGLST_DESG,
  coun(*) as "Count_AGVGLST_PIDM"
from AGVGLST
where AGVGLST_DESG = '1125'
group by 
  AGVGLST_DESG 

任何其他过滤字段都会添加到选择列表和分组列表中,然后添加到where子句中。

答案 2 :(得分:0)

如果您运行此查询该怎么办?

SELECT 
    COUNT(a.AGVGLST_PIDM) "Count_AGVGLST_PIDM",
FROM AGVGLST a
WHERE 
    a.AGVGLST_DESG      = '1125'
AND a.AGVGLST_FISC_CODE = '2010'
AND NOT EXISTS(
            SELECT 'x'
            FROM 
                agvglst b
            WHERE b.agvglst_pidm = a.agvglst_pidm
            AND b.agvglst_desg <> '1125'
            AND b.agvglst_fisc_code = '2010'
        )
相关问题