案例陈述组由

时间:2014-11-10 20:31:48

标签: sql oracle case-statement

我想找一年的NET_AMT .. NET_AMT是SUM(SAL_AMT)/ SUM(INC_AMT).. 我有以下查询,我得到了NET_AMT的12个值,因为我按DATE_KEY分组..但我必须只获得一年的一条记录..

SELECT 
DIM_NUM, 
SN_NUM,
REL_NUM,
SUM(INS_AMT) AS INS,
CASE WHEN DATE_KEY BETWEEN 200801 AND 200812 THEN 
(CASE WHEN SUM(INC_AMT) <> 0 THEN SUM(SAL_AMT)/SUM(INC_AMT)END) END AS NET_AMT
FROM 
Table_A
GROUP BY 
DIM_NUM, 
SN_NUM,
REL_NUM,
DATE_KEY;

2 个答案:

答案 0 :(得分:1)

这是您的查询:

SELECT DIM_NUM, SN_NUM, REL_NUM, SUM(INS_AMT) AS INS,
       (CASE WHEN DATE_KEY BETWEEN 200801 AND 200812
             THEN (CASE WHEN SUM(INC_AMT) <> 0 THEN SUM(SAL_AMT)/SUM(INC_AMT) END)
        END) AS NET_AMT
FROM Table_A
GROUP BY DIM_NUM, SN_NUM, REL_NUM, DATE_KEY;

将条件移至where子句并从date_key移除group by

SELECT DIM_NUM, SN_NUM, REL_NUM, SUM(INS_AMT) AS INS,
       (CASE WHEN SUM(INC_AMT) <> 0 THEN SUM(SAL_AMT)/SUM(INC_AMT)
        END) AS NET_AMT
FROM Table_A
WHERE DATE_KEY BETWEEN 200801 AND 200812
GROUP BY DIM_NUM, SN_NUM, REL_NUM;

编辑:

如果人们第一次提出正确的问题,那真的会更容易。假设DATE_KEY是一个数字:

SELECT DIM_NUM, SN_NUM, REL_NUM, SUM(INS_AMT) AS INS,
       LEFT(CAST(DATE_KEY as VARCHAR(255)), 4) as Year,
       (CASE WHEN SUM(INC_AMT) <> 0 THEN SUM(SAL_AMT)/SUM(INC_AMT)
        END) AS NET_AMT
FROM Table_A
GROUP BY DIM_NUM, SN_NUM, REL_NUM, LEFT(CAST(DATE_KEY as VARCHAR(255)), 4)

答案 1 :(得分:0)

更像这样:

SELECT 
  DIM_NUM, 
  SN_NUM,
  REL_NUM,
  SUM(INS_AMT) AS INS,
  SUM(CASE WHEN DATE_KEY BETWEEN BETWEEN 200801 AND 200812 THEN SAL_AMT ELSE 0 END) /
  SUM(CASE WHEN DATE_KEY BETWEEN BETWEEN 200801 AND 200812 THEN INC_AMT ELSE 0 END) AS NET_AMT
FROM Table_A
GROUP BY DIM_NUM, SN_NUM, REL_NUM, DATE_KEY;