GROUP BY CASE语句输出

时间:2013-01-09 05:35:09

标签: oracle plsql group-by

如何更改下面的脚本,以便我可以使用QTR_PCT给出的GROUP BY YR,QTR,CODE来获得我想要的输出?

CREATE VIEW REPORTS.MY_VIEW
(YR, QTR, QTR_PCT, CODE)
AS 
SELECT YR, QTR
, CASE WHEN PCTPERF>=85 THEN ROUND(AVG(PCTPERF)) 
  ELSE NULL
  END QTR_PCT
, CODE
FROM ANOTHER_VIEW
GROUP BY YR, QTR, PCTPERF, CODE
ORDER BY CODE ASC;

实际输出:(我没有列QTR_PCT列)

+------+-----+------+
|   YR | QTR | CODE |
+------+-----+------+
| 2012 |   1 | 1039 | 
| 2012 |   1 | 1039 | 
| 2012 |   1 | 1039 |
| 2012 |   2 | 1039 | 
| 2012 |   2 | 1039 | 
| 2012 |   2 | 1039 |  
+------+-----+------+

期望的输出:(我没有包括列QTR_PCT)

+------+-----+------+
|   YR | QTR | CODE |
+------+-----+------+
| 2012 |   1 | 1039 | 
| 2012 |   2 | 1039 | 
+------+-----+------+

1 个答案:

答案 0 :(得分:1)

我不确定我理解你的问题,但也许这可以帮助,尝试:

SELECT YR, qtr, code,max(qtr_pct)  aa
FROM (
SELECT YR, qtr, code, pctref,  CASE WHEN pctref >= 85 THEN round(avg(pctref) over (partition BY YEAR, qtr, code))
  ELSE NULL END qtr_pct
FROM ANOTHER_VIEW) t
GROUP BY YR, qtr, code;

Here is a sqlfiddle demo