안녕하세요.
추운데 감기 조심하세요 ㅎㅎ
다름이 아니라 다음과 같은 경우를 쿼리로 작성 가능할까요? 아무리 구글링을 해보고 열심히 노력해도 안되네요 ㅠㅠ
다음과 같은 테이블이 있다고 가정했을 때..
Column A | Column B | Column C | Column D |
A | 0 | 0 | 0 |
B | 1 | 1 | 2 |
C | 1 | 2 | 2 |
D | 0 | 0 | 0 |
E | 1 | 1 | 3 |
F | 1 | 2 | 3 |
G | 1 | 3 | 3 |
H | 0 | 0 | 0 |
Column A 와 B 는 원래 Table 에 있는 값들이고, C와 D 는 Query 로 구해야 하는 값입니다.
Column C 는 Column B 의 값을 Sum 하는데.. 자기 Row 수보다 위 Row 값들을 하나씩 더해가는 것입니다. 단, 0을 만나면 Sum 을 그만두고요.
Column D 는 Column B 의 값을 Sum 하는데.. 자기 Row 위/아래로 0이 오기 전까지의 연속된 1이 있는 값들을 다 더하는 겁니다.
혹시 이걸 쿼리로 만들수 있을까요? Column C 나 Column D 중 되는 것이 있다면 그것만이라도 알 수 있을까요?
부탁드립니다. ㅠㅠ
감사합니다~~
<Table>
WITH T AS
(
SELECT 'A' AS A, 0 AS B FROM DUAL UNION ALL
SELECT 'B', 1 FROM DUAL UNION ALL
SELECT 'C', 1 FROM DUAL UNION ALL
SELECT 'D', 0 FROM DUAL UNION ALL
SELECT 'E', 1 FROM DUAL UNION ALL
SELECT 'F', 1 FROM DUAL UNION ALL
SELECT 'G', 1 FROM DUAL UNION ALL
SELECT 'H', 0 FROM DUAL
)
WITH t AS ( SELECT 'A' AS a, 0 AS b FROM DUAL UNION ALL SELECT 'B', 1 FROM DUAL UNION ALL SELECT 'C', 1 FROM DUAL UNION ALL SELECT 'D', 0 FROM DUAL UNION ALL SELECT 'E', 1 FROM DUAL UNION ALL SELECT 'F', 1 FROM DUAL UNION ALL SELECT 'G', 1 FROM DUAL UNION ALL SELECT 'H', 0 FROM DUAL ) , t1 AS (SELECT ROWNUM rn, a, b FROM t) , t2 AS (SELECT ROWNUM rn, a, b , MAX (DECODE (b, 0, ROWNUM)) OVER (ORDER BY ROWNUM ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) bef0 , MIN (DECODE (b, 0, ROWNUM)) OVER (ORDER BY ROWNUM ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING) aft0 FROM t) SELECT a, b , DECODE (b, 0, 0, (SELECT SUM (b) FROM t1 WHERE t1.rn BETWEEN bef0 AND t2.rn)) c , DECODE (b, 0, 0, (SELECT SUM (b) FROM t1 WHERE t1.rn BETWEEN bef0 AND aft0)) d FROM t2
더 쉬운 방법이 있을 것 같은데.. 머리가 안 돌아가네요;
WITH t AS ( SELECT 'A' AS a, 0 AS b FROM DUAL UNION ALL SELECT 'B', 1 FROM DUAL UNION ALL SELECT 'C', 1 FROM DUAL UNION ALL SELECT 'D', 0 FROM DUAL UNION ALL SELECT 'E', 1 FROM DUAL UNION ALL SELECT 'F', 1 FROM DUAL UNION ALL SELECT 'G', 1 FROM DUAL UNION ALL SELECT 'H', 0 FROM DUAL ) SELECT a , b , DECODE (b, 0, 0, SUM (b) OVER (ORDER BY ROWNUM ROWS BETWEEN rn - NVL (bef0, 0) PRECEDING AND CURRENT ROW)) c , DECODE (b, 0, 0, SUM (b) OVER (ORDER BY ROWNUM ROWS BETWEEN rn - NVL (bef0, 0) PRECEDING AND GREATEST(NVL (aft0, 0) - rn, 0) FOLLOWING)) d FROM (SELECT ROWNUM rn, a, b , MAX (DECODE (b, 0, ROWNUM)) OVER (ORDER BY ROWNUM ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) bef0 , MIN (DECODE (b, 0, ROWNUM)) OVER (ORDER BY ROWNUM ROWS BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING) aft0 FROM t)