比较列并动态查找表中的差异

问题描述 投票:0回答:2

我有一个有3列的表,第一列是一些参数,剩下的3是这些参数的最后1周计数,内容类似如下。第一行是来自oracle的表列。我必须计算2个日期的差异。

Parameter    20190319   20190315    20190313
============================================
A    682            614         600         
B    194            194         190     
C    62             62          0

输出应如下所示,

Parameter    20190319   (20190319-20190315) 20190315    (20190315-20190313) 20190313
========================================================
 A   682            68      614         14      600         
 B   194            0       194         4       190     
 C   62             0        62         62      0

这里棘手的部分是日期不按顺序排列,最多可达7天,我们必须从列名动态计算。如果可以在oracle中完成,那将是很棒的。谢谢!!

text-processing scripting perl oracle
2个回答
0
投票

像这样的东西?

#!/usr/bin/perl

use strict;
use warnings;

while (<DATA>) {
        chomp;
        my @line = split;
        my $diff1 = $line[1] - $line[2];
        my $diff2 = $line[2] - $line[3];
        print "$line[0]\t$line[1]\t$diff1\t$line[2]\t$diff2\t$line[3]\n";
}

__DATA__
A    682            614         600         
B    194            194         190     
C    62             62          0

产量

$ perl t.pl 
A   682 68  614 14  600
B   194 0   194 4   190
C   62  0   62  62  0

您问题中C行的输出看起来不正确。你是怎么计算的?


0
投票

最后,我能够编写解决方案,谢谢大家的支持!特别是Ashish :)

================================================== ========================= DECLARE

x varchar2(2000):= NULL; y varchar2(4000):= NULL;

开始

for i in(select column_id,column_name,lead(column_name,1) OVER (ORDER BY column_id) next_column 
    from all_tab_cols where table_name='TABLE_NAME' and column_name not in ('Parameter'))
loop

    if i.next_column != 'NULL' then
        x := x||'NVL("'||i.column_name||'",0) as "'||i.column_name||'",NVL("'||i.column_name||'", 0)-NVL("'||i.next_column||'", 0) as "'||i.column_name||'~",';
    else
        x := x||'NVL("'||i.column_name||'",0) as "'||i.column_name||'"';
    end if;    
 end loop;

y :=  'create  table TABLE_NAME_NEW as select Parameter,'|| x || ' from TABLE_NAME
order by  Parameter';
--dbms_output.put_line('y :'||y);  
execute immediate y;

结束;

/

© www.soinside.com 2019 - 2024. All rights reserved.