ORACLE DECODE具有多个表达式或多个解码

时间:2014-10-21 14:50:49

标签: decode

我在Oracle表格中有以下数据,我正在尝试根据TYPE& amp; QT专栏。

TYPE QT STATUS  CNT
---- -- ------  ---
E    A  YES     123
E    A  NO     2540
E    D  YES       2
E    D  NO      787
O    A  YES     884
O    A  NO     6957
O    D  YES      25
O    D  NO     1360

看起来我的预期输出现在不同了......如下所示:

TYPE    TOTAL   A   A&Y
----    -----   ----    -----
E+O     12678   10504   1007
E       3452     2663    123

我的旧oracle sql在下面,但在计算百分比时输出错误:

SELECT * FROM (
    SELECT NVL(SUM(DECODE(A.QT,'A',A.CNT,'D',A.CNT)),0) AS "TOTAL",
    NVL(SUM(DECODE(A.QT,'A',A.CNT)),0) AS "A ALL",
    NVL(SUM(DECODE(A.QT,'A',ROUND(100*(NVL(A.CNT,0)/ A.CNT),2))),0) "A ALL %",
    NVL(SUM(DECODE(A.STATUS,'E',A.CNT)),0) AS "E TOTAL",
    NVL(SUM(DECODE(A.STATUS,'E',DECODE(A.QT,'A',A.CNT))),0) AS "E & A TOTAL"",
    NVL(SUM(DECODE(A.STATUS,'E',ROUND(100 * SUM((DECODE(A.QT,'A',A.CNT)) / SUM(A.CNT)),3))),0) "E & A %"
    FROM ALLIN A)

1 个答案:

答案 0 :(得分:0)

您可以使用公用表表达式以更易读的方式重写查询;

WITH cte AS (
  SELECT 
    SUM(cnt) total,
    SUM(DECODE(qt,   'A', cnt, 0))      a_all,
    SUM(DECODE(type, 'E', cnt, 0))      e_total,
    SUM(DECODE(type||qt, 'EA', cnt, 0)) ea_total
  FROM allin
)
SELECT 
  total, a_all, ROUND(a_all/total*100, 2) a_percent,
  e_total, ea_total, ROUND(ea_total/e_total*100, 2) ea_percent
FROM cte;

此查询生成预期结果,并且更容易阅读和调试。 EA部分假设qt和type都是一个字母,因此它们的串联与EA匹配。如果不是这样,我建议使用CASE代替' la;

SUM(CASE WHEN type = 'E' AND qt = 'A' THEN cnt ELSE 0 END) ea_total

An SQLfiddle to test with