我是PL / SQL的新手
我有这样的代码
SELECT f.code,f.date,f.amt, row_number() OVER (PARTITION BY f.code ORDER BY f.date DESC) ranki
FROM advance.alloc f
并显示
CODE DATE AMT ranki
122 12/31/2016 3 1
122 12/31/2015 7 2
122 12/31/2014 3 3
123 6/30/2015 3 1
125 6/30/2015 2 1
125 12/31/2014 8 2
逻辑就是这个
if DATE = 12/__/__ AND ranki = 1 THEN ranki 1, so 122 picks 12/31/2016 3
if DATE = 6/30/__ AND ranki = 1 AND if ranki = 2 exists THEN then pick the second one,so 125 picks 12/31/2014 8
if 6/30__ and ranki is ONLY 1 shows Blank on date LIKE 123
所以我想展示
122 12/31/2016 3
123 __________ 3
125 12/31/2014 8
我如何像这个PL / SQL一样编码?
WHEN to_char(af.date,'MM') = 12 AND af.ranki = 1 THEN af.date END
我可以编写第一个逻辑,但我无法弄清楚如何编写逻辑的其余部分
由于
答案 0 :(得分:2)
为什么在PL / SQL中?或者你的意思是"在Oracle SQL"? (下面的解决方案使用标准分析函数,因此它不是特定于Oracle的。)
除了ranki
之外,还可以通过分析函数添加更多信息。使用ranki = 1
从行中提取月份,以及每个code
的总计数。然后WHERE子句可以一步一步地遵循您的逻辑。
with
f ( code, dt, amount ) as (
select 122, to_date('12/31/2016', 'mm/dd/yyyy'), 3 from dual union all
select 122, to_date('12/31/2015', 'mm/dd/yyyy'), 7 from dual union all
select 122, to_date('12/31/2014', 'mm/dd/yyyy'), 3 from dual union all
select 123, to_date( '6/30/2015', 'mm/dd/yyyy'), 3 from dual union all
select 125, to_date( '6/30/2015', 'mm/dd/yyyy'), 2 from dual union all
select 125, to_date('12/31/2014', 'mm/dd/yyyy'), 8 from dual
)
-- End of simulated data (for testing purposes only, not part of the solution).
-- SQL query begins BELOW THIS LINE.
select code, case when mth = 12 or ranki = 2 then dt end as dt, amount
from ( select code, dt, amount,
first_value(extract (month from dt))
over (partition by code order by dt desc) as mth,
row_number() over (partition by code order by dt desc) as ranki,
count(*) over (partition by code) as cnt
from f
)
where mth = 12 and ranki = 1
or cnt = 1
or mth = 6 and ranki = 2
;
CODE DT AMOUNT
---- ---------- ------
122 12/31/2016 3
123 3
125 12/31/2014 8