我有一个包含许多列的表,我计算列上的特定名称,如果该名称不在列表中,我想将其显示为零,但不能进入列表。
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)
不起作用
答案 0 :(得分:4)
您可以按名称对结果进行分组,然后将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
答案 1 :(得分:0)
然后你必须使用其他语法:
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
答案 2 :(得分:0)
这应该适用于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
答案 3 :(得分:0)
您可以创建一个包含所有有效名称的表,例如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;