oracle12c,sql,count(*)和sum()之间的差异

时间:2020-07-09 07:21:21

标签: sql count sum oracle12c

告诉我sql1和sql2之间的区别:

sql1:

select count(1)
from table_1 a
inner join table_2 b on a.key = b.key where a.id in (
  select id from table_1 group by id having count(1) > 1
) 

sql2:

select sum(a) from (
  select count(1) as a
  from table_1 a
  inner join table_2 b on a.key = b.key group by a.id having count(1) > 1
)

为什么输出不一样?

2 个答案:

答案 0 :(得分:1)

查询甚至都不相似。他们有很大的不同。让我们检查第一个:

select count(1)
from table_1 a
inner join table_2 b
on a.key = b.key 
where a.id in (
  select id from table_1 group by id having count(1) > 1
) ;

您首先要进行内部联接:

select count(1) 
from table_1 a 
inner join table_2 b 
on a.key = b.key

在这种情况下,可以使用count(1),count(id),count(*)等价。您正在计算两个表中的常见元素:具有相同键字段的那些元素。

之后,您将执行此操作:

where a.id in (
      select id from table_1 group by id having count(1) > 1
    ) 

换句话说,table_1表中的每个“ id”必须至少两次。

最后,您正在执行此操作:

select count(1)

换句话说,计算那些元素。因此,您已将其翻译成英文:

  1. 获取表_1的每个记录,并与表_2的记录配对以获取标识,并仅获取匹配的记录
  2. 对于上述结果,仅过滤出table_1的ID出现多次的元素
  3. 计算结果

让我们看看第二个查询会发生什么:

select sum(a) from (
  select count(1) as a
  from table_1 a
  inner join table_2 b 
  on a.key = b.key 
  group by a.id 
  having count(1) > 1
);

您正在进行相同的内部联接:

  select count(1) as a
  from table_1 a
  inner join table_2 b 
  on a.key = b.key 

但是,您正在按表的ID对其进行分组:

  group by a.id 

,然后仅过滤出出现多次的那些元素:

  having count(1) > 1

到目前为止,结果是一组记录,它们在两个表中具有相同的键字段,但按id分组:这意味着仅输出table_b中至少两次的字段此加入。之后,您按id分组,将这些结果折叠到table_1.id字段中并计数结果。我认为很少有记录能符合这个严格的标准。

最后,将所有这些集合加起来。

答案 1 :(得分:0)

当使用count(*)时,将对所有行进行计数。 SUM()函数是一个聚合函数,它返回一组值中所有或不同值的总和。

相关问题