【问题标题】:Query subselect at least one查询子选择至少一项
【发布时间】:2018-11-10 17:22:43
【问题描述】:

我有一个名为 motion_history 的表(代表汽车的运动(注册、出售、暂停、修复、销毁))。我想获取一家公司的信息 每辆车都卖给谁了。

这是我的桌子(选择 *)

code_car  date_movement  type_movement  current_company_code
  6000     01/01/2010       NEW              5
  6000     01/01/2012       REPARATION       5
  6000     01/11/2015       SOLD             8
  6000     01/01/2017       DESTROYED        8
  4444     01/05/2000       NEW              10
  4444     01/05/2000       SUSPENDED        10
  4444     01/05/2015       SOLD             5
  4444     01/07/2015       RENOVATION       5
  4444     09/12/2015       SOLD             18
  ....      ...             ...              ...

因此,如果我希望在确定的时间(2015 年 1 月 1 日至 2015 年 1 月 1 日至 2015 年 2 月 31 日)公司 5 的所有汽车销售,这将是结果:

  code_car  date_movement  type_movement  current_company_code
  6000     01/11/2015       SOLD             8
  4444     09/12/2015        SOLD             18

这是我的问题。首先,我获取某天从公司 5 获得的所有汽车。然后,我获取所有“已售出”的动作,如果某天成为公司的一部分,我想为每辆售出的汽车获取 5。

select 
    code_car,date_movement,type_movement,current_company_code 
from 
    movement_history where code_car in (
        (select code_car from movement_history where current_company_code = 5)) and 
code_car IN     
        (select code_car from movement_history where type_movement = 
        'SOLD' and code_car <> 5 and date_movement > to_Date('01-01-2015','dd/mm/yyyy') and date_movement < to_Date('31-12-2015','dd/mm/yyyy'));

如果某天售出的每辆汽车至少有 5 次成为公司的一部分,我想我做的部分很糟糕。

有什么建议吗?非常感谢。

【问题讨论】:

  • “31-02-2015”应该代表什么日期?

标签: sql oracle subquery


【解决方案1】:

我明白了。 current_company_code得到这辆车的公司。所以,你想使用LAG()

select mh.*
from (select mh.*,
             lag(mh.current_company_code) over (partition by mh.code_car order by date_movement) as prev_ccc
      from movement_history mh
     ) mh
where mh.type_movement = 'SOLD' and
      mh.date_movement >= date '2015-01-01' and
      mh.date_movement < date '2016-01-01' and
      mh.prev_ccc = 5;

【讨论】:

  • 不使用lag还有可能吗?
  • @artyuiberwaf 。 . . lag() 是最简单的解决方案,应该有最好的性能。我认为没有理由不使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-11
  • 1970-01-01
  • 2016-07-03
  • 1970-01-01
  • 1970-01-01
  • 2021-11-11
  • 2018-02-11
相关资源
最近更新 更多