计算同一列中记录的差异

时间:2014-07-12 11:50:29

标签: sql oracle11g

我有一张桌子如下。

DATE        DIVISION            KPI      ACTUAL
01-07-2014  HYDRO       1   100
01-07-2014  HYDRO       2   200
01-07-2014  HYDRO       3   300
01-07-2014  HYDRO       4   400
01-07-2014  THERMAL     1   500
01-07-2014  THERMAL     2   600
01-07-2014  THERMAL     3   700
01-07-2014  THERMAL     4   800

我的要求如下。

WHEN KPI IS 1, THEN ACTUAL.
WHEN KPI IS 2, THEN DIVIDE KPI 2/KPI 1 OF ACTUAL.   200/100 =2 
WHEN KPI IS 3, THEN DIVIDE KPI 4/ KPI 3 OF ACTUAL.  400/300 = 1.33
WHEN KPI IS 4, THEN ACTUAL.

上述计算对于每个部门都是相同的。

请提供您的价值建议以编写SQL以达到要求。

谢谢, 拉吉

2 个答案:

答案 0 :(得分:0)

CASE WHEN KPI IN (1, 4) THEN ACTUAL
     WHEN KPI = 2 THEN KPI / MIN(CASE WHEN KPI = 1 AND KPI <> 0 THEN ACTUAL END) 
                             OVER (PARTITION BY DATE, DIVISION)
     WHEN KPI = 3 THEN KPI / MIN(CASE WHEN KPI = 3 AND KPI <> 0 THEN ACTUAL END) 
                             OVER (PARTITION BY DATE, DIVISION)
END

您可能需要更改PARTITION BY,但看起来您想要计算每个DATE / DVISION组合。

答案 1 :(得分:0)

您需要一个案例陈述以及获取各种kpi值。我会使用分析函数来做到这一点:

select t.*,
       (case when kpi = 1 then actual
             when kpi = 2 then actual / actual1
             when kpi = 3 then actual / actual4
             when kpi = 4 then actual
        end)
from (select t.*,
             max(case when kpi = 1 then actual end) over (partition by date, division) as actual1,
             max(case when kpi = 4 then actual end) over (partition by date, division) as actual4
      from table t
     ) t