I am trying to query the below data set :
Sample input :
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')
Expected out :
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
Logic Based : for a particular sn if easyrfqy ='P' or 'E' or 'N' then Pref for a particular sn if it has a ecaty 1 then set 1 for all rows for that sn for a particular sn if it had easyrfqy 'YES' then set all rows as YES
I tried this :
select * from
(
select *,row_number()over(partition by sn order by ecat desc) as rn from t
)x where x.rn=1
Here is the SQl fiddle : http://www.sqlfiddle.com/#!6/e104d/1
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
It depends on the assumption that the string 'YES' is greater than 'NO' in the actual language environment the query is executed, and similarly 'Pref' > 'NP'. If it is not true for any reason, than more tricky approch is needed, eg:
decode(max(case when ps in ('P', 'E', 'N') then 1 else 0 end) over (partition by sn), 1, 'Pref', 0, 'NP') as ps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.