Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
与group by相比,在sql中使用过分区_Sql_Oracle_Group By_Count_Database Partitioning - Fatal编程技术网

与group by相比,在sql中使用过分区

与group by相比,在sql中使用过分区,sql,oracle,group-by,count,database-partitioning,Sql,Oracle,Group By,Count,Database Partitioning,给定下面的表格创建代码,是否有其他方法向用户显示相同的结果 select b.*, count(*) over (partition by colour) bricks_total from bricks b; 使用分组依据和计数(*)?这种情况有什么不同 create table bricks ( brick_id integer, colour varchar2(10), shape varchar2(10), weight int

给定下面的表格创建代码,是否有其他方法向用户显示相同的结果

select b.*, count(*) over (partition by colour) bricks_total 
from bricks b;
使用
分组依据
计数(*)
?这种情况有什么不同

create table bricks 
(
     brick_id integer,
     colour   varchar2(10),
     shape    varchar2(10),
     weight   integer
);

insert into bricks values (1, 'blue', 'cube', 1);
insert into bricks values (2, 'blue', 'pyramid', 2);
insert into bricks values (3, 'red', 'cube', 1);
insert into bricks values (4, 'red', 'cube', 2);
insert into bricks values (5, 'red', 'pyramid', 3);
insert into bricks values (6, 'green', 'pyramid', 1);

commit;

此查询将每一行中每种颜色的总数放入:

select b.*, count(*) over (partition by colour) as bricks_total
from bricks b;
在使用窗口函数之前,典型的解决方案是相关子查询:

select b.*,
       (select count(*) from bricks b2 where b2.colour = b.colour) as bricks_total
from bricks b;
您还可以使用
join
和聚合来表达这一点:

select b.*, bb.bricks_total
from bricks b join
     (select bb.colour, count(*) as bricks_total
      from bricks bb
      group by bb.colour
     ) bb
     using (colour);
这些不是100%相同。不同之处在于,即使值为
NULL
,原始代码也会返回
color
的计数。此代码返回
0

因此,更精确的等价物是:

select b.*,
       (select count(*)
        from bricks b2
        where b2.colour = b.colour or
              b2.colour is null and b.colour is null
       ) as bricks_total
from bricks b;

非常感谢您的努力,但是b2代表什么呢?@AbbasFadhil。这是一个*表别名*(.我的意思是,我不明白为什么在[b2.color=b.color]中使用它,当它们都引用相同的值时,有没有办法不使用其他别名?就像说[if 1=1->return value]@AbbasFadhil…这就是相关子查询的工作方式。