使用子查询在SQL Oracle中创建新列-有什么建议吗?

wbrvyc0a  于 2023-06-05  发布在  Oracle
关注(0)|答案(2)|浏览(199)

我的表中有列Yearmonthcodetypeclntamount。我想导出列clntamount_der
Table view

我希望clntamount中的110值与type = Total在列clntamount_der中,其中type = base和其余两行(adj和total)为零。
请帮助逻辑。
我试过case语句,但它不工作,也许一个子查询将工作

cvxl0en2

cvxl0en21#

您可以使用条件最大窗口函数如下:

select t.*, 
  case 
    when TYPE = 'BASE' 
       then max(case when TYPE = 'TOTAL' then CLNTAMOUNT end) over
               (partition by YearMonth, Code)
       else 0
    end as clntamount_der
from tbl t
order by 
  YearMonth, Code,
  case TYPE
    when 'BASE' then 1
    when 'ADJUST' then 2
    when 'TOTAL' then 3
  end

demo
此外,似乎TOTAL是其他类型(BASE,ADJUST)的总和,在这种情况下,最好在运行中计算TOTAL(而不是将其存储为单独的行),以避免数据不一致。也就是说,当你更新CLNTAMOUNT的值,其中type = 'BASE',你如何将其反映到type = 'TOTAL'的值?
考虑以下情况,而不将TOTAL类型存储在表中。

select d.*
  from
(
  select t.YearMonth, t.Code, t.Type, t.CLNTAMOUNT,
    case 
      when TYPE = 'BASE' 
         then sum(t.CLNTAMOUNT) over (partition by t.YearMonth, t.Code)
         else 0
      end as clntamount_der
  from tbl t
  
  union all
  
  select t.YearMonth, t.Code, 'TOTAL',
          sum(t.CLNTAMOUNT), 0 
  from tbl t
  group by t.YearMonth, t.Code
) d
order by 
  d.YearMonth, d.Code,
  case d.TYPE
    when 'BASE' then 1
    when 'ADJUST' then 2
    when 'TOTAL' then 3
  end

demo

rseugnpd

rseugnpd2#

可以使用case语句和lead()函数

select *, case when TYPE = 'BASE' then lead(clntamount,2)
over (order by (select null)) else 0 end as clntamount_der
from test

fiddle

相关问题