我有下面显示的Oracle SQL
select *
from a
where a.description in ('Rebook All (1)', 'Created stock identifier')
and a.date between '03/18/2017 00:00:01' AND '03/25/2017 00:00:00'
and a.unit = '38240007294677'
现在结果可以多次描述,如下面的单位编号,或者可以有1个描述。当它同时具有单位编号的描述时,我只需要选择“重新预订全部(1)”(此描述可以存在多次/多行,如下面的结果所示)描述不是“创建的库存标识符”及其相关细节来自表a
。当它只有1个描述时,如果不存在'Rebook All(1)',则选择'Created stock identifier',反之亦然。
如何选择?
Date Description
3/20/2017 10:11:12.769000 AM Created stock identifier
3/20/2017 10:10:47.775000 AM Created stock identifier
3/20/2017 10:10:47.782000 AM Created stock identifier
3/20/2017 8:14:41.696000 PM Rebook all (1)
3/20/2017 8:14:41.885000 PM Rebook all (1)
3/20/2017 8:13:51.622000 PM Rebook all (1)
如果有单位编号的描述('Rebook All(1)','Created stock identifier'),那么我需要得到的结果如下('Rebook All(1)')及其所有行,但是,如果单位编号只有一个描述('Rebook All(1)','Created stock identifier'),那么就得到那个描述 -
如果同时具有单位编号的描述('Rebook All(1)','Created stock identifier'),则仅获得('Rebook All(1)'),如下所示 -
3/20/2017 8:14:41.696000 PM Rebook all (1)
3/20/2017 8:14:41.885000 PM Rebook all (1)
3/20/2017 8:13:51.622000 PM Rebook all (1)
如果单位编号只有1个描述'创建的库存标识符',那么只获得'创建的库存标识符' -
3/20/2017 10:11:12.769000 AM Created stock identifier
3/20/2017 10:10:47.775000 AM Created stock identifier
3/20/2017 10:10:47.782000 AM Created stock identifier
答案 0 :(得分:2)
这是达到您要求的一种方式。我使用RANK() OVER
窗口函数根据DESC
顺序中的描述对单位记录进行排名。
SELECT *
FROM (
SELECT UNIT
, DESCRIPTION
, RANK() OVER (PARTITION BY UNIT ORDER BY DESCRIPTION DESC) RN
FROM MY_TABLE A
WHERE A.DESCRIPTION IN ('Rebook all (1)'
, 'Created stock identifier')
AND A.DATE BETWEEN '03/18/2017 00:00:01' AND '03/25/2017 00:00:00'
--AND A.UNIT = '38240007294677'
)
WHERE RN = 1
答案 1 :(得分:0)
从Oracle 12c开始:
select a.*
from a
where a.unit = '38240007294677'
and a.description in ('Rebook All (1)', 'Created stock identifier')
and a.date >= date '2017-01-18'
and a.date < date '2017-03-25'
order by case when a.description = 'Rebook All (1)' then 1 else 2 end
fetch first row with ties;