我有这种奇怪的情况,我想用ie计数器显示所有列表值 我的测试表内容
name, misc
A, blah
B, 123
A, asd
现在,此查询将仅为A和B获取结果,但如何显示C“结果”
select name, count(*) from table
where name in ('A','B','C')
结果我想得到
A 2
B 1
C 0
这个案子让我疯狂了一天。 请帮忙
干杯, 丹
答案 0 :(得分:1)
我认为你必须为这种类型的查询使用外连接,例如:
WITH mylist AS (SELECT 'A' name FROM DUAL
UNION ALL SELECT 'B' FROM DUAL
UNION ALL SELECT 'C' FROM DUAL)
SELECT l.name, COUNT(t.name)
FROM mylist l
LEFT JOIN mytable t ON l.name = t.name
GROUP BY l.name
您可以使用表对象而不是UNION ALL:
CREATE TYPE name_list_t AS TABLE OF VARCHAR2(30);
/
SELECT l.name, COUNT(t.name)
FROM (SELECT column_value name FROM TABLE(name_list_t('A', 'B', 'C')) l
LEFT JOIN mytable t ON l.name = t.name
GROUP BY l.name
答案 1 :(得分:0)
您可以通过外部连接包含值列表的表来完成此操作:
WITH lookup AS (
SELECT decode(LEVEL
,1,'A'
,2,'B'
,3,'C') col1
FROM dual
CONNECT BY LEVEL <= 3
)
,test AS (
SELECT decode(LEVEL
,1,'A'
,2,'A'
,3,'B') col1
,decode(LEVEL
,1,'blah'
,2,'123'
,3,'asd') col2
FROM dual
CONNECT BY LEVEL <= 3
)
SELECT lookup.col1,count(test.col1)
FROM lookup
,test
WHERE lookup.col1 = test.col1 (+)
GROUP BY lookup.col1
;
返回:
A 2
B 1
C 0
在我的示例中,“查找”是动态生成的。您可以使用此方法,也可以更好地使用自己的值列表表。
答案 2 :(得分:0)
从此处获取分割器功能:how to convert csv to table in oracle
然后
select a.column_value, count(t.name)
from table(splitter('A,B,C')) a
left join table t on (t.name = a.column_value)
group by a.column_value