【问题标题】:find deleted positiones effectively in sql oracle在 sql oracle 中有效查找已删除的位置
【发布时间】:2021-02-05 23:08:18
【问题描述】:

我有一张巨大的桌子,上面有数百万个采购订单。 我也尝试从性能角度寻找更好的方法来实现目标。

这里是一些示例数据,每个订单有几个位置,位置 0 是标题,位置 1-2 是一些项目。在某些情况下,买家下订单有多个仓位,然后他可以调整这些仓位,例如删除所有仓位,在这种情况下,所有仓位都会得到flaf 'y' 和仓位0(在我们的例子中,6 月份的 order2) .在某些情况下,他不会像我们的简单数据集(6 月的 order1)中那样只删除所有这些。

create table orders (
po varchar2(6),
pos number,
flag char(1),
datum date
)

insert into orders values ('order1',0,'n',to_date('01-01-2020','dd-MM-yyyy'));
insert into orders values ('order1',1,'n',to_date('01-01-2020','dd-MM-yyyy'));
insert into orders values ('order1',2,'n',to_date('01-01-2020','dd-MM-yyyy'));
insert into orders values ('order1',0,'n',to_date('01-06-2020','dd-MM-yyyy'));
insert into orders values ('order1',1,'y',to_date('01-06-2020','dd-MM-yyyy'));
insert into orders values ('order1',2,'n',to_date('01-06-2020','dd-MM-yyyy'));

insert into orders values ('order2',0,'n',to_date('01-01-2020','dd-MM-yyyy'));
insert into orders values ('order2',1,'n',to_date('01-01-2020','dd-MM-yyyy'));
insert into orders values ('order2',2,'n',to_date('01-01-2020','dd-MM-yyyy'));
insert into orders values ('order2',0,'y',to_date('01-06-2020','dd-MM-yyyy'));
insert into orders values ('order2',1,'y',to_date('01-06-2020','dd-MM-yyyy'));
insert into orders values ('order2',2,'y',to_date('01-06-2020','dd-MM-yyyy'));

目标是找到至少一个已删除位置的订单名称(位置 0 除外,这将通过删除所有位置 1-2 自动设置)

在我们的例子中,结果只是 order1

这个当然不行

select distinct po from orders where pos <> 0 and flag = 'y';

解决方案是子查询或相关子查询

select distinct po from orders
where pos <> 0 and flag = 'y'
and po not in (
select distinct po from orders
where pos = 0 and flag = 'y');

但我想知道从性能角度来看是否有更好的解决方案,因为 该表被查询了两次,并且有大量的 PO,这当然太慢了

有什么想法吗?

【问题讨论】:

  • 我不明白。重复的日期是什么意思?为什么第一个查询不起作用?

标签: sql oracle performance subquery correlated-subquery


【解决方案1】:

你可能需要条件聚合

select po
from tab
group by po
having max(case when pos <> 0 then flag end) = 'y' -- at least one deleted position
   and max(case when pos =  0 then flag end) = 'n' -- but no deleted header

【讨论】:

    【解决方案2】:

    使用聚合:

    select po
    from orders o
    group by po
    having sum(case when pos = 1 and flag = 'y' then 1 else 0 end) = 0 and
           sum(case when flag = 'y' then 1 else 0 end) > 0;
       
    

    【讨论】:

      猜你喜欢
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      相关资源
      最近更新 更多