当列中的行为空时,ORACLE显示计数为零
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了当列中的行为空时,ORACLE显示计数为零相关的知识,希望对你有一定的参考价值。
我有一个包含许多列的表,我计算列上的特定名称,如果该名称不在列表中,我想将其显示为零,但不能进入列表。
SELECT Names, COUNT (*)
FROM NAMESTABLE
WHERE names IN
('Jenny',
'Penny',
'George',
'James',
'Jessica',
'Monica',
'Erica')
AND
adeddate BETWEEN '2014/10/15' AND '2014/10/16'
GROUP BY names
NAMES || COUNT(*)
Jenny || 33
Penny || 4
George || 25
James || 87
所以我想杰西卡,莫妮卡,埃里卡作为ZERO甚至这些名字都不在COLUMN
Names || Count(*)
Jenny || 33
Penny || 4
George || 25
James || 87
Jessica || 0
Monica || 0
Erica || 0
nvl(count(*),0)
不起作用
答案
您可以按名称对结果进行分组,然后将结果left join
到您的名称表中以填充空白:
SELECT rn.name, NVL(cnt, 0)
FROM (SELECT 'Jenny' AS name FROM dual
UNION ALL
SELECT 'Penny' FROM dual
UNION ALL
SELECT 'George' FROM dual
UNION ALL
SELECT 'James' FROM dual
UNION ALL
SELECT 'Jessica' FROM dual
UNION ALL
SELECT 'Monica' FROM dual
UNION ALL
SELECT 'Erica' FROM dual) rn
LEFT JOIN (SELECT name, COUNT(*) AS cnt
FROM namestable
WHERE adeddate BETWEEN '2014/10/15' AND '2014/10/16'
GROUP BY name) n ON n.name = rn.name
另一答案
然后你必须使用其他语法:
SELECT t.Names, COUNT(n.Names)
FROM (
SELECT 'Jenny' AS names FROM DUAL UNION ALL
SELECT 'Penny' FROM DUAL UNION ALL
SELECT 'George' FROM DUAL UNION ALL
SELECT 'James' FROM DUAL UNION ALL
SELECT 'Jessica' FROM DUAL UNION ALL
SELECT 'Monica' FROM DUAL UNION ALL
SELECT 'Erica' FROM DUAL
) t
LEFT OUTER JOIN NAMESTABLE n
ON n.names = t.names AND n.adeddate BETWEEN '2014/10/15' AND '2014/10/16'
GROUP BY t.names
另一答案
这应该适用于CTE ..
WITH CTE AS
(SELECT 'Jenny' Names FROM dual UNION ALL
SELECT 'Penny' FROM dual UNION ALL
SELECT 'George' FROM dual UNION ALL
SELECT 'James' FROM dual UNION ALL
SELECT 'Jessica' FROM dual UNION ALL
SELECT 'Monica' FROM dual UNION ALL
SELECT 'Erica' FROM dual)
SELECT CTE.names, coalesce(count(NT.Names),0)
FROM CTE
LEFT JOIN NAMESTABLE NT
on CTE.Names = NT.Names
and adeddate BETWEEN '2014/10/15' AND '2014/10/16'
GROUP BY CTE.Names
另一答案
您可以创建一个包含所有有效名称的表,例如valid_names表。然后使用outerjoin加入你的namestable。例如:
select valid_names.name, count(1)
from namestable, valid_names
where valid_names.name=namestable.name (+)
group by valid_names.name
order by valid_names.name;
以上是关于当列中的行为空时,ORACLE显示计数为零的主要内容,如果未能解决你的问题,请参考以下文章
在 Oracle PL/SQL 中,当列的其余值相等时,我可以交换表中两个不同行的同一列的值吗?