我正在尝试查询以下数据集:
示例输入:
create table t(sn varchar(100),easyrfqy varchar(10),ecaty int,ps varchar(10))
insert into t values('abc','NO',0,'E'),('abc','YES',1,'N'),('abc','NO',0,'W'),
('def','NO',1,'E'),('def','NO',0,'X'),('xyz','NO',1,'X')
期待:
sn easyrfqy_update ecaty_update ps
abc YES 1 Pref
abc YES 1 Pref
abc YES 1 Pref
def NO 1 Pref
def NO 1 Pref
xyz NO 1 NP
基于逻辑:对于特定的sn,如果easyrfqy ='P'或'E'或'N'则为Pref 对于特定的sn,如果它有一个ecaty 1然后为该sn的所有行设置1 对于特定的sn,如果它具有easyrfqy'YES',则将所有行设置为YES
我试过了:
select * from
(
select *,row_number()over(partition by sn order by ecat desc) as rn from t
)x where x.rn=1
这是SQl小提琴:http://www.sqlfiddle.com/#!6/e104d/1
答案 0 :(得分:0)
select t.sn,
max(easyrfqy) over (partition by sn) as easyrfqy_update,
max(ecaty) over (partition by sn) as ecaty_update,
max(case when ps in ('P', 'E', 'N') then 'Pref' else 'NP' end) over (partition by sn) as ps
from t
这取决于在执行查询的实际语言环境中字符串'YES'大于'NO'的假设,并且类似地'Pref'> 'NP'。如果由于任何原因不成立,则需要更棘手的方法,例如:
decode(max(case when ps in ('P', 'E', 'N') then 1 else 0 end) over (partition by sn), 1, 'Pref', 0, 'NP') as ps