我试图在sql developer(emp table)中得到这个结果:
TOTAL 1980 1981 1982 1983
-------- --------- --------- --------- ---------
14 1 10 2 1
但我得到了:
TOTAL 1980 1981 1982 1983
-------- --------- --------- --------- ---------
13 1 10 2 1
指望整个桌子给我14:
SELECT COUNT(*) FROM EMP;
为什么这种情况下的计数会返回13而不是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;
答案 0 :(得分:0)
我认为你想要条件聚合:
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;
注意:
GROUP BY HIREDATE
。您似乎只想要一行输出。DECODE()
是特定于Oracle的。条件表达式的ANSI标准是CASE
。COUNT(*)
内嵌套了聚合函数(SUM()
)。这是导致问题的原因。此版本应解决此问题。