group 조회 0 3 1,354

by DISTINCT [2018.04.09 10:39:04]


select 한 값

name 1week 2week 3week
scott 2018-04-02    
scott 2018-04-03    
scott   2018-04-10  
scott     2018-04-16
john 2018-04-03    
john     2018-04-16
kim   2018-04-10  

 

변경하고 싶은 결과

name 1week 2week 3week
scott 2018-04-02 2018-04-10 2018-04-16
scott 2018-04-03    
john 2018-04-03   2018-04-16
kim   2018-04-10  

이런식으로 변경 하고 싶은데...이런류는 처음이라 머리가 아프네요...

날짜 와 사람은 가변적이라고 할때 이런식의 그룹을 만들려면 어떻게 해야 할지 궁금합니다. 

 

by 우리집아찌 [2018.04.09 11:13:02]
-- 답에만 맞췄습니다.
WITH T ( name,week1,week2,week3 )AS (
SELECT 'scott' , '2018-04-02' , '' ,''  FROM DUAL UNION ALL
SELECT 'scott' , '2018-04-03' , '' ,''  FROM DUAL UNION ALL
SELECT 'scott' , '' , '2018-04-10' ,''  FROM DUAL UNION ALL
SELECT 'scott' , '' , '' ,'2018-04-16'  FROM DUAL UNION ALL
SELECT 'john' , '2018-04-03' , '' ,''  FROM DUAL UNION ALL
SELECT 'john' , '' , '' ,'2018-04-16'  FROM DUAL UNION ALL
SELECT 'kim' , '' , '2018-04-10' ,''  FROM DUAL 
)

SELECT * 
  FROM ( SELECT RN
              , NAME
              , CASE WHEN ROW_NUMBER() OVER(PARTITION BY NAME , WEEK1 ORDER BY RN ) = 1 THEN WEEK1 END WEEK1  
              , CASE WHEN ROW_NUMBER() OVER(PARTITION BY NAME , WEEK2 ORDER BY RN ) = 1 THEN WEEK2 END WEEK2  
              , CASE WHEN ROW_NUMBER() OVER(PARTITION BY NAME , WEEK3 ORDER BY RN ) = 1 THEN WEEK3 END WEEK3  
           FROM (SELECT NAME
                      , RN 
                      , LAST_VALUE(WEEK1 IGNORE NULLS) OVER(PARTITION BY NAME ORDER BY RN DESC) WEEK1
                      , LAST_VALUE(WEEK2 IGNORE NULLS) OVER(PARTITION BY NAME ORDER BY RN DESC) WEEK2
                      , LAST_VALUE(WEEK3 IGNORE NULLS) OVER(PARTITION BY NAME ORDER BY RN DESC) WEEK3
                   FROM (SELECT ROWNUM RN , T.* FROM T ) AA
                ) A
        )
 WHERE WEEK1 IS NOT NULL OR WEEK2 IS NOT NULL OR WEEK3 IS NOT NULL       
 ORDER BY RN

 


by 우리집아찌 [2018.04.09 11:20:01]

NAME과 WEEK기준으로 값이 중복이 발생되면 무시됩니다.. ㅡㅡ;


by 마농 [2018.04.09 11:32:01]
SELECT name
     , MIN(week1) week1
     , MIN(week2) week2
     , MIN(week3) week3
  FROM (SELECT name
             , week1, week2, week3
             , ROW_NUMBER() OVER(PARTITION BY name
                                            , CASE WHEN week1 IS NOT NULL THEN 1
                                                   WHEN week2 IS NOT NULL THEN 2
                                                   WHEN week3 IS NOT NULL THEN 3
                                               END
                                     ORDER BY week1, week2, week3, ROWNUM
                                 ) rn
          FROM t
        )
 GROUP BY name, rn
 ORDER BY name, rn
;

 

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