2017-08-03 180 views
0

我是新来的PL/SQLPL/SQL,CASE语句或if语句

我有这样

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 

我可以编写第一个逻辑,但我无法弄清楚如何休息

感谢

回答

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 
+0

Wowwwwwwwwwwwwwwwwwwwwww!新奇!谢谢!!! –