1
2
3
4
5
6
7
8
9
10
11
12
13
14 |
SELECT 1 AS COL1, 10 AS COL2, 'A' AS COL3 FROM DUAL
UNION ALL
SELECT 2 AS COL1, 20 AS COL2, 'A' AS COL3 FROM DUAL
UNION ALL
SELECT 3 AS COL1, 30 AS COL2, 'A' AS COL3 FROM DUAL
UNION ALL
SELECT 4 AS COL1, 40 AS COL2, 'A' AS COL3 FROM DUAL
UNION ALL
SELECT 5 AS COL1, 50 AS COL2, 'B' AS COL3 FROM DUAL
UNION ALL
SELECT 6 AS COL1, 60 AS COL2, 'B' AS COL3 FROM DUAL
UNION ALL
SELECT 7 AS COL1, 70 AS COL2, 'C' AS COL3 FROM DUAL
; |
예를 들기 위해 위와같이 임의의 테이블을 만들었습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 |
SELECT COL3, SUM(COL2), AVG(COL2)
FROM (
SELECT 1 AS COL1, 10 AS COL2, 'A' AS COL3 FROM DUAL
UNION ALL
SELECT 2 AS COL1, 20 AS COL2, 'A' AS COL3 FROM DUAL
UNION ALL
SELECT 3 AS COL1, 30 AS COL2, 'A' AS COL3 FROM DUAL
UNION ALL
SELECT 4 AS COL1, 40 AS COL2, 'A' AS COL3 FROM DUAL
UNION ALL
SELECT 5 AS COL1, 50 AS COL2, 'B' AS COL3 FROM DUAL
UNION ALL
SELECT 6 AS COL1, 60 AS COL2, 'B' AS COL3 FROM DUAL
UNION ALL
SELECT 7 AS COL1, 70 AS COL2, 'C' AS COL3 FROM DUAL ) TEMP
GROUP BY COL3
; |
GROUP BY 를 사용해서 그룹별 합계와 평균을 위처름 구할 수 있습니다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 |
SELECT COL1, COL2, COL3
,SUM(COL2) OVER (PARTITION BY COL3) AS "그룹합계"
,AVG(COL2) OVER (PARTITION BY COL3) AS "그룹평균"
,AVG(COL2) OVER (PARTITION BY COL3) - COL2 AS "평균과의차"
FROM
(
SELECT 1 AS COL1, 10 AS COL2, 'A' AS COL3 FROM DUAL
UNION ALL
SELECT 2 AS COL1, 20 AS COL2, 'A' AS COL3 FROM DUAL
UNION ALL
SELECT 3 AS COL1, 30 AS COL2, 'A' AS COL3 FROM DUAL
UNION ALL
SELECT 4 AS COL1, 40 AS COL2, 'A' AS COL3 FROM DUAL
UNION ALL
SELECT 5 AS COL1, 50 AS COL2, 'B' AS COL3 FROM DUAL
UNION ALL
SELECT 6 AS COL1, 60 AS COL2, 'B' AS COL3 FROM DUAL
UNION ALL
SELECT 7 AS COL1, 70 AS COL2, 'C' AS COL3 FROM DUAL
) TEMP
; |
그룹별 합계와 평균을 해당 row에 사용할 때, 위처럼 사용할 수 있습니다.
번외로, DISTINCT가 걸려있는 데이터들에 대해서 PARTITION BY를 사용하면, DISTINCT를 무시한 모든 DATA에 대해서 PARTITION BY를 수행합니다. DISTINCT보다 PARTITION BY가 먼저 수행된다는 이야기.. 복잡한 SQL수정 하면서 데이터가 이상하게 나왔는데 그게 DISTINCT 때문인 것을 발견한 적이 있네요.
'공대 (Logical Life) > 프로그래밍' 카테고리의 다른 글
Oracle(오라클) BI 컬럼명 변경시 유의해야 할 버그 (0) | 2013.05.02 |
---|---|
oracle pl/sql pipelined를 사용한 table 형태 반환 function (0) | 2012.11.13 |
oracle sql문에서 주석 다는 습관 (0) | 2012.11.08 |
java에서 String 변수를 equals 함수로 비교할 때, NullPointerException 방지 (0) | 2012.06.20 |
제11회 2011 한국 자바 개발자 컨퍼런스 (0) | 2011.06.17 |