我希望SQLplus count(*)返回零值
我使用的是Oracle 10.2,有以下问题:我希望SQLplus count(*)返回零值,sql,count,Sql,Count,我使用的是Oracle 10.2,有以下问题: select h.company, count(*) from history h where h.status = '2' and h.substatus = '0' and h.timestamp > '2012-01-01' and h.timestamp < '2012-02-01' group by h.company having (h.c
select h.company, count(*)
from history h
where h.status = '2'
and h.substatus = '0'
and h.timestamp > '2012-01-01'
and h.timestamp < '2012-02-01'
group by h.company
having (h.company = 'AAA')
or (h.company = 'BBB')
or (h.company = 'CCC')
order by h.company
选择h公司,计数(*)
从历史h
其中h.status='2'
而h.substatus='0'
时间戳>'2012-01-01'
和h.时间戳<'2012-02-01'
h公司集团
拥有(h.公司=‘AAA’)
或(h.company='BBB')
或(h.company='CCC')
h公司订购
这将计算AAA、BBB或CCC公司的任何客户达到特定点(状态=2)的次数。假设BBB没有(零)个客户这样做,结果将返回两行计数(AAA和CCC) 我想要的:我希望查询返回所有3家公司的行,即使计数为零 很抱歉,查询的布局很奇怪。它也可以与MS Excel一起使用 编辑:对不起。。咖啡因太少了。在查询的后半部分将“客户”更改为“公司” 澄清:通过组合“h.company”和“h.customer”(或使用客户表(客户c)中的相同方法,如“c.company”和“c.customer”)使客户具有唯一性 编辑2:更新的代码
select c.company, count(*)
from companyregister c
left join history h on h.company = c.company
where h.status = '2'
and h.substatus = '0'
and h.timestamp > '2012-01-01'
and h.timestamp < '2012-02-01'
group by c.company
having (c.company = 'AAA')
or (c.company = 'BBB')
or (c.company = 'CCC')
order by c.company
选择c.公司,计数(*)
来自公司注册中心
h.company=c.company上的左连接历史h
其中h.status='2'
而h.substatus='0'
时间戳>'2012-01-01'
和h.时间戳<'2012-02-01'
c公司集团
拥有(c.公司=‘AAA’)
或(c.公司='BBB')
或(c.公司=‘CCC’)
c公司订购
上面的两组代码将产生两行,如下所示:
AAA630
CCC3020
我想表示BBB,但由于它们在历史记录中没有行,因此不会显示。在customer表上进行左联接。我不知道您将其命名为什么,但如下所示:
select c.company, count(h.customer)
from customer as c
left join history as h on h.customer = c.customer
...
另一种选择是在计数时使用条件。我不确定是否有任何其他条件与状态一起需要,但类似于以下内容:
select company, sum(case status when '2' then 1 else 0 end)
from history
where substatus = '0'
and timestamp > '2012-01-01'
and timestamp < '2012-02-01'
and customer in ('AAA', 'BBB', 'CCC')
group by customer
order by customer
选择公司、金额(案例状态为“2”,然后为1,否则为0结束)
来自历史
其中substatus='0'
时间戳>'2012-01-01'
和时间戳<'2012-02-01'
以及('AAA'、'BBB'、'CCC'中的客户)
按客户分组
按客户订购
count(*)
将计算不正确的值(特别是对于那些不在历史记录中的客户,它将返回1
。它应该是count(h.customer)
@a_horse\u with_no\u name:是的,你当然是对的。我在写答案时忘记了,我现在已经更正了。:)我使用了您提供的代码,但由于我在帖子中提供了一个带有一些错误的查询,所以不得不尝试一些修改。@Guffa-我得到了要运行的查询,但它仍然不会显示历史上没有条目的公司。我得到了公司AAA和CCC的金额,但BBB没有列出(因为他们没有客户)@Numpus:您使用的是哪个版本?您可以在问题的编辑中添加当前使用的查询吗?在查询中出现了一些错误。将“客户”更改为“公司”。对此表示抱歉。