ORACLE PL / SQL PIVOT程序

时间:2017-12-12 20:12:37

标签: oracle stored-procedures plsql pivot

我正在尝试编写一个Oracle PL / SQL过程来计算一个简单的混淆矩阵表。我准备好了标记数据,基本上是两列0和1,实际值与预测值。

我能够通过简单的枢轴计算它(我认为最直接的选择):

SELECT * FROM 
( SELECT ACTUAL_VALUE, PREDICTED_VALUE
FROM MY_TABLE
)
PIVOT (
COUNT(PREDICTED_VALUE)
FOR PREDICTED_VALUE IN (1, 0))
ORDER BY ACTUAL_VALUE;

现在我试图将所有这些“插入”DECLARE,BEGIN ......框架但没有成功。甚至可以创建程序来计算这个支点吗?

提前感谢任何建议!

1 个答案:

答案 0 :(得分:0)

我不得不使用游标和循环。并以这种方式进行计算。所以关闭这一个。最后加上3个总结计算。 谢谢

CREATE OR REPLACE PROCEDURE "mydb"."C_MATRIX" 
IS
    CURSOR MY_DATA IS
        SELECT ACTUAL_CARD, PREDICTED_VALUE FROM my_table; 
    my_data_rec my_data%rowtype; 

    fp pls_integer := 0;
    tp pls_integer := 0;
    fn pls_integer := 0;
    tn pls_integer := 0;

BEGIN 
    OPEN my_data; 
    LOOP 
        FETCH my_data INTO my_data_rec; 
        EXIT WHEN my_data%notfound; 
            IF my_data_rec.ACTUAL_CARD = 0 and my_data_rec.PREDICTED_VALUE = 0 then
                tn := tn + 1;
            elsif my_data_rec.ACTUAL_CARD = 0 and my_data_rec.PREDICTED_VALUE = 1 then
                fn := fn + 1;
            elsif my_data_rec.ACTUAL_CARD = 1 and my_data_rec.PREDICTED_VALUE = 1 then
                tp := tp + 1;      
            elsif my_data_rec.ACTUAL_CARD = 1 and my_data_rec.PREDICTED_VALUE = 0 then
                fp := fp + 1;        
            end if;
    END LOOP; 

    dbms_output.put_line
    ('Number of false Positives: ' ||fp || '  Number of true Positives: ' ||tp  || '       Total numbers of records: ' ||(fp + tp) );
    dbms_output.put_line
    ('Number of false Negatives: ' ||fn || '   Number of true Negatives: ' ||tn  || '       Total numbers of records: ' ||(fn + tn ));
    dbms_output.put_line(' ');
    dbms_output.put_line
    (' Incorrect predictions: ' || (fp + fn) || '  Correct predictions: ' || (tp + tn) );
    dbms_output.put_line(' ');
    dbms_output.put_line(' Acurracy: ' || round((((tn + tp) / (tn + tp + fn + fp)) * 100),2) || '%');
    dbms_output.put_line(' Precision: ' || round(((tp / (tp + fp)) * 100),2) || '%');
    dbms_output.put_line(' Recall: ' || round(((tp / (tp + fn)) * 100),2) || '%');
END; 
/