我需要在这里做一个小调整,不确定是否可以完成。在下文中,如果没有' 001'行,那么我只想要那个顺序的1行,但是当有001时我确实想要那个和下一个按照最早的时间。
CREATE VIEW rklib.clspaytp AS Select * from
(
Select x.*,
row_number() over (partition by otord#
order by case ottrnc when '001' then 1 else 2 end
, ottrnd, ottrt
)
as RowN
from rklib.clspaytpp x
) a
where a.RowN in (1,2)
我们有这样的数据:
+-------+-------+------+------+
| Order | Codes | Rep | Time |
+=======+=======+======+======+
| 123 | 001 | Buck | 0900 |
+-------+-------+------+------+
| 123 | CCW | BUCK | 0909 |
+-------+-------+------+------+
| 123 | FGH | BUCK | 0904 |
+-------+-------+------+------+
这里我们想要001和FGH。 FGH早于CCW 5。。
现在如果001不在那里,那么我们想要的就是FGH,而不是2.我们只想要一个2fer,其中一个是001。
答案 0 :(得分:0)
这是一种可能的解决方案。
create table clspaytpp (
otord# decimal (5, 0),
ottrnc char (3),
ottrnd char (10),
ottrt decimal (4, 0));
insert into clspaytpp values
(123, '001', 'Buck', 0900),
(123, 'CCW', 'BUCK', 0909),
(123, 'FGH', 'BUCK', 0904);
insert into clspaytpp values
(124, 'CCW', 'BUCK', 0909),
(124, 'FGH', 'BUCK', 0904);
with code1 as (
select otord# as otord1
from clspaytpp
where ottrnc = '001'
group by otord#
order by otord#)
select *
from clspaytpp
where otord# in (select otord1 from code1)
and ottrnc = '001'
union
select *
from clspaytpp o
where ottrt in (select min(ottrt) from clspaytpp i where i.otord# = o.otord# and ottrnc <> '001')
and ottrnc <> '001'
order by 1, 2;