【问题标题】:PL/SQL, CASE statement or if statementPL/SQL、CASE 语句或 if 语句
【发布时间】:2017-08-04 04:28:25
【问题描述】:

我是 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

我可以编写第一个逻辑,但我不知道如何编写其余的逻辑

谢谢

【问题讨论】:

    标签: plsql oracle11g


    【解决方案1】:

    为什么在 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 1970-01-01
      • 2022-07-20
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多