GROUP BY有COUNT SQL不按预期工作

时间:2015-01-20 13:26:43

标签: sql oracle

我正在尝试运行查询以从PSOPRDEFN中提取b.OPRID,其中EMPLID在ps_DEDUCTION_BAL中至少有一行符合以下查询中的以下条件。但是,当我运行它时,它不会返回我认为不正确的数据。我的查询有问题吗?

SELECT b.OPRID
  FROM ps_DEDUCTION_BAL a, PSOPRDEFN b
 WHERE     a.PLAN_TYPE = '4A'
       AND a.DED_YTD > 0
       AND a.BALANCE_YEAR >= '2015'
       AND a.BALANCE_PERIOD >= '6'
       AND a.EMPLID = b.emplid
       AND b.OPRID LIKE 'ZZ%'
       GROUP BY b.OPRID
       HAVING COUNT(*) > 1

4 个答案:

答案 0 :(得分:2)

使用exists

SELECT b.OPRID
FROM pPSOPRDEFN b
WHERE OPRID LIKE 'ZZ%' AND
      EXISTS (SELECT 1
              FROM s_DEDUCTION_BAL a
              WHERE a.PLAN_TYPE = '4A' AND a.DED_YTD > 0 AND
                    a.BALANCE_YEAR >= '2015' AND a.BALANCE_PERIOD >= '6' AND
                    a.EMPLID = b.emplid
             );

这应该比您的版本具有更好的性能,这需要聚合。

答案 1 :(得分:0)

至少应该有一行:

HAVING COUNT(*) >= 1

HAVING COUNT(*) > 1

答案 2 :(得分:0)

不需要GROUP BY,DISTINCT会做的伎俩

SELECT DISTINCT b.OPRID
FROM ps_DEDUCTION_BAL a, PSOPRDEFN b
 WHERE     a.PLAN_TYPE = '4A'
       AND a.DED_YTD > 0
       AND a.BALANCE_YEAR >= '2015'
       AND a.BALANCE_PERIOD >= '6'
       AND a.EMPLID = b.emplid
       AND b.OPRID LIKE 'ZZ%'

答案 3 :(得分:0)

您在此处执行的表之间的连接:

a.EMPLID = b.emplid

实际上会删除PSOPRDEFNps_DEDUCTION_BAL中没有匹配行的所有行,因此简单DISTINCT会执行:

SELECT DISTINCT b.OPRID
  FROM ps_DEDUCTION_BAL a, PSOPRDEFN b
 WHERE     a.PLAN_TYPE = '4A'
   AND a.DED_YTD > 0
   AND a.BALANCE_YEAR >= '2015'
   AND a.BALANCE_PERIOD >= '6'
   AND a.EMPLID = b.emplid
   AND b.OPRID LIKE 'ZZ%'