Sql 查询子选择至少一个
我有一个名为movement_history的表格,它代表了汽车的登记、销售、暂停、维修和销毁。我想得到一家公司的信息 这已经把每辆车卖给了谁 这是我的桌子*Sql 查询子选择至少一个,sql,oracle,subquery,Sql,Oracle,Subquery,我有一个名为movement_history的表格,它代表了汽车的登记、销售、暂停、维修和销毁。我想得到一家公司的信息 这已经把每辆车卖给了谁 这是我的桌子* code_car date_movement type_movement current_company_code 6000 01/01/2010 NEW 5 6000 01/01/2012 REPARATION 5 6000 01/1
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年2月31日的确定时间内获得5号公司的所有汽车销售,结果如下:
code_car date_movement type_movement current_company_code
6000 01/11/2015 SOLD 8
4444 09/12/2015 SOLD 18
这是我的疑问。首先,我从公司获得了所有的汽车。然后,我获得所有“售出”的运动,如果某一天是公司的一部分,我想获得每辆售出的汽车的运动
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'));
如果某一天售出的每一辆车都至少有一次是公司的一部分,我想我做得很糟糕
有什么建议吗?非常感谢。我明白了。当前的公司代码是获得汽车的公司。因此,您要使用滞后:
2015年2月31日应该代表什么日期?不使用滞后是否有任何可能性?@artyuiberwaf。滞后是最简单的解决方案,应该具有最佳性能。我看没有理由不使用它。
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;