如何将Concat字符串转换为Oracle中的数字

时间:2017-07-17 07:13:01

标签: oracle

我的Table_A如下所示

SALDO_AWAL_TAHUN   YTD_AMOUNT_JAN  YTD_AMOUNT_FEB  YTD_AMOUNT_MAR  BRANCH_ID
100                200             300             400             001a

YTD_AMOUNT_JAN表示1月份的金额,YTD_AMOUNT_FEB表示2月份的金额等我想要的是我可以根据月份进行选择。我已经将功能定义为月份作为参数。

FUNCTION GET_MONTH_NAME (P_MONTH INT)
      RETURN VARCHAR
   IS
      V_RESULT   VARCHAR (20);
   BEGIN
      SELECT   CASE
                  WHEN P_MONTH = 1 THEN 'JAN'
                  WHEN P_MONTH = 2 THEN 'FEB'
                  WHEN P_MONTH = 3 THEN 'MAR'
                  WHEN P_MONTH = 4 THEN 'APR'
                  WHEN P_MONTH = 5 THEN 'MAY'
                  WHEN P_MONTH = 6 THEN 'JUN'
                  WHEN P_MONTH = 7 THEN 'JUL'
                  WHEN P_MONTH = 8 THEN 'AUG'
                  WHEN P_MONTH = 9 THEN 'SEP'
                  WHEN P_MONTH = 10 THEN 'OCT'
                  WHEN P_MONTH = 11 THEN 'NOV'
                  ELSE 'DEC'
               END
        INTO   V_RESULT
        FROM   DUAL;


      RETURN V_RESULT;
   END;

从我做的功能。例如,我得到MAR (march) as V_MONTH,然后我想在我的选择查询中连接字符串'YTD_AMOUNT_' + MAR(我从函数中得到),如下所示:

SELECT SUM(NVL (SALDO_AWAL_TAHUN, 0) + (NVL ('YTD_AMOUNT_'
  || GET_MONTH_NAME (3), 0))) AS value
FROM Table_A

我希望结果是:

500 (SALDO_AWAL_TAHUN + YTD_AMOUNT_MAR  )

但它显示了我"数字无效" 我在谷歌搜索了很多关于我的案例,但我还没有找到它

2 个答案:

答案 0 :(得分:1)

取消包含每月数据的列

select t.*, substr(t.mon, 12, 3) as m
from table_a unpivot(val for mon in("YTD_AMOUNT_JAN",
                                    "YTD_AMOUNT_FEB",
                                    "YTD_AMOUNT_MAR")) t
/* result:

SALDO_AWAL_TAHUN  BRANCH_ID MON             VAL M
100               001a      YTD_AMOUNT_JAN  200 JAN
100               001a      YTD_AMOUNT_FEB  300 FEB
100               001a      YTD_AMOUNT_MAR  400 MAR

*/

现在您可以轻松选择所需的数据:

select res
  from (select substr(t.mon, 12, 3) as m,
               t.saldo_awal_tahun + val as res
          from (select *
                  from table_a unpivot(val for mon in("YTD_AMOUNT_JAN",
                                                      "YTD_AMOUNT_FEB",
                                                      "YTD_AMOUNT_MAR"))) t)
 where m = GET_MONTH_NAME(2);

答案 1 :(得分:0)

您必须使用函数名称并传递变量,如下所示:

SELECT NVL(SALDO_AWAL_TAHUN,0)+ NVL('YTD_AMOUNT_'|| GET_MONTH_NAME(3),0)来自Table_A的AS值;