简体   繁体   中英

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM