Stefan Ca Stefan Ca - 14 days ago 6
SQL Question

Count(*) returns (rows number - 1) in sql developer(ORACLE)

I am trying to get this result in sql developer(emp table):

TOTAL 1980 1981 1982 1983
-------- --------- --------- --------- ---------
14 1 10 2 1


but I am getting :

TOTAL 1980 1981 1982 1983
-------- --------- --------- --------- ---------
13 1 10 2 1


Counting on the entire table gives me 14:

SELECT COUNT(*) FROM EMP;


Why does the count in this case return 13 not 14 ?

SELECT COUNT(*) TOTAL,
SUM(DECODE(EXTRACT(YEAR FROM HIREDATE),1980,COUNT(*))) "1980",
SUM(DECODE(EXTRACT(YEAR FROM HIREDATE),1981,COUNT(*))) "1981",
SUM(DECODE(EXTRACT(YEAR FROM HIREDATE),1982,COUNT(*))) "1982",
SUM(DECODE(EXTRACT(YEAR FROM HIREDATE),1983,COUNT(*))) "1983"
FROM EMP GROUP BY HIREDATE;

Answer

I think you want conditional aggregation:

SELECT COUNT(*) TOTAL,
       SUM(CASE WHEN EXTRACT(YEAR FROM HIREDATE) = 1980 THEN 1 ELSE 0 END) as "1980",
       SUM(CASE WHEN EXTRACT(YEAR FROM HIREDATE) = 1981 THEN 1 ELSE 0 END) as "198`",
       SUM(CASE WHEN EXTRACT(YEAR FROM HIREDATE) = 1982 THEN 1 ELSE 0 END) as "1982",
       SUM(CASE WHEN EXTRACT(YEAR FROM HIREDATE) = 1983 THEN 1 ELSE 0 END) as "1983"
FROM EMP;

Notes:

  • There is no need to GROUP BY HIREDATE. You only seem to want one row of output.
  • DECODE() is Oracle-specific. The ANSI standard for conditional expressions is CASE.
  • You have nested aggregation functions (COUNT(*) inside SUM()). This is the cause of your problem. This version should fix the issue.
Comments