특정컬럼값 복사하기 0 2 1,409

by 농부지기 [SQL Query] [2019.08.01 20:19:48]


WITH V_COP AS
( SELECT 'A01' AS ORG_CD, 300  AS GOAL, '1' AS SEQ FROM DUAL UNION ALL
  SELECT 'A01' AS ORG_CD, NULL AS GOAL, '0' AS SEQ  FROM DUAL UNION ALL
  SELECT 'A01' AS ORG_CD, NULL AS GOAL, '0' AS SEQ  FROM DUAL UNION ALL
  SELECT 'C05' AS ORG_CD, 600  AS GOAL, '1' AS SEQ  FROM DUAL UNION ALL
  SELECT 'C05' AS ORG_CD, NULL AS GOAL, '0' AS SEQ  FROM DUAL UNION ALL
  SELECT 'C05' AS ORG_CD, NULL AS GOAL, '0' AS SEQ  FROM DUAL
)

SELECT A.ORG_CD, B.GOAL
  FROM (
		SELECT *
		  FROM V_COP 
	   ) A
     , (
		SELECT *
		  FROM V_COP 
		 WHERE GOAL IS NOT NULL
	    ) B
 WHERE A.ORG_CD = B.ORG_CD ;
		 

sql을 보면 ORGA_CD, GOAL, SEQ 컬럼 3개가 존재 할때
ORGA_CD는 모든 레코드에 존재 하지만 GOAL 은 하나만 존재 합니다.
이때 GOAL이 NULL  또는 SEQ=0 인 경우에는    [같은 ORGA_CD] 이면서 [SEQ=1]인 레코드
에서 GOAL을 복사하고 싶습니다.
UNION 이나, JOIN으로 안하고..  혹시 함수가 있을까 해서요.

위 SQL문장은 JOIN을 이용한 SQL입니다.
그래서 JOIN을 하지 않고, [함수]를 이용해서 위 결과처럼 나오게 하고 싶은 거죠.

부탁 합니다.

by 농부지기 [2019.08.02 09:02:53]

자문자답]

SELECT ORG_CD
     , MAX(GOAL) OVER (PARTITION BY ORG_CD) AS GOAL
  FROM V_COP ;


by 야신 [2019.08.04 23:28:36]

-- 약간 조건만 추가했습니다.

WITH V_COP AS
( SELECT 'A01' AS ORG_CD, 300  AS GOAL, '1' AS SEQ FROM DUAL UNION ALL
  SELECT 'A01' AS ORG_CD, NULL AS GOAL, '0' AS SEQ  FROM DUAL UNION ALL
  SELECT 'A01' AS ORG_CD, NULL AS GOAL, '0' AS SEQ  FROM DUAL UNION ALL
  SELECT 'C05' AS ORG_CD, 600  AS GOAL, '1' AS SEQ  FROM DUAL UNION ALL
  SELECT 'C05' AS ORG_CD, NULL AS GOAL, '0' AS SEQ  FROM DUAL UNION ALL
  SELECT 'C05' AS ORG_CD, NULL AS GOAL, '0' AS SEQ  FROM DUAL
)
 
SELECT org_cd, CASE WHEN seq = 0 AND goal IS NULL THEN
                 MAX(goal) OVER(PARTITION BY org_cd)
               ELSE
                 goal
               END AS goal
  FROM V_COP

댓글등록
SQL문을 포맷에 맞게(깔끔하게) 등록하려면 code() 버튼을 클릭하여 작성 하시면 됩니다.
로그인 사용자만 댓글을 작성 할 수 있습니다. 로그인, 회원가입