无法从Oracle SQL获得正确的输出

时间:2011-03-22 16:56:11

标签: sql oracle count

我有一个包含field1,field2,field3,...的表格,我需要计算field1中的项目数量,以便返回表格中出现6次或更少的所有记录(field1,filed2,field3,...)

我的SQL代码是:

SELECT field1, field2, field3, count(field1) CNT
FROM myTable
WHERE trunc(date)  = tp_date(‘03/22/2011’,’mm/dd/yyyy’)
GROUP BY field1
HAVING COUNT(field1)  <  7;

我从上面的代码得到的输出是从表中返回的所有记录不是我所期望的?任何帮助将不胜感激!!

3 个答案:

答案 0 :(得分:1)

我认为您需要使用子查询:

SELECT field1, field2, field3, 
FROM myTable
WHERE trunc(date)  = tp_date(‘03/22/2011’,’mm/dd/yyyy’)
AND field1 in 
   (SELECT field1
    FROM mytable
    GROUP BY field1
    HAVING COUNT(field1)  <  7); 

答案 1 :(得分:1)

WITH tmp AS
(
    SELECT field1, COUNT(1) as CountOfField1
    FROM myTable
    WHERE trunc(date) = tp_date(‘03/22/2011’,’mm/dd/yyyy’)
    GROUP BY field1
    HAVING COUNT(field1) < 7
)
SELECT  mytable.field1, mytable.field2, mytable.field3, tmp.CountOfField1
FROM    myTable 
        INNER JOIN tmp 
            ON myTable.Field1 = tmp.Field1

答案 2 :(得分:0)

另一种方法:

SELECT t.field1, t.field2, t.field3, 
FROM myTable t
WHERE trunc(t.date) = tp_date(‘03/22/2011’,’mm/dd/yyyy’)
  AND EXISTS
  ( SELECT *
    FROM mytable t2
    WHERE t2.field1 = t.field1
      AND trunc(t2.date) = tp_date(‘03/22/2011’,’mm/dd/yyyy’)
    GROUP BY t2.field1
    HAVING COUNT(t2.field1)  <  7
  )
;