중복데이터 제거 0 6 1,335

by 쥬발자 [SQL Query] union [2022.07.20 14:37:48]


캡처.PNG (10,744Bytes)

table 1은 항목리스트가 담긴 테이블이고 table2는 항목리스트에 대한 결과값이 담긴테이블 입니다.

최종 목표로 하고자 하는 것은 항목리스트에 대한 결과값이 없어도 항목리스트를 모두 뽑아내려고 합니다...

 

select target_one
       , target_two
       , '' as target_three
from table1
union
select target_one
       , target_two
       , target_three
from table2

이런식으로 코드를 짜서  결과물이 첨부파일 왼쪽처럼 나오게 되는데요.

오른쪽 표처럼 target_one 컬럼에서 중복되는 순번의 경우 값이 있는 데이터만 남는 형식으로 만들고 싶은데요 가능할까요..?

제가 현재 만든 쿼리가 맞는것은 아니고 일단 생각나는 대로 만들어본겁니다..

by 우리집아찌 [2022.07.20 14:45:11]
select target_one
     , target_two
     , max(target_three) target_three
  from (select target_one
			 , target_two
			 , '' as target_three
		  from table1

		union all

		select target_one
			 , target_two
			 , target_three
		 from table2
		) a
  group by 	target_one , target_two  

 


by pajama [2022.07.20 14:49:45]

안녕하세요. row_number 함수를 썼습니다.

select target_one, target_two, target_three
from (
select target_one, target_two, target_three, 
        row_number() over (partition by target_two order by target_three) rn
from t
)
where rn = 1
order by target_one
;

 


by 마농 [2022.07.20 14:51:42]
-- Outer Join --
SELECT a.target_one
     , a.target_two
     , b.target_three
  FROM table1 a
  LEFT OUTER JOIN table2 b
    ON a.target_one = b.target_one
;
http://gurubee.net/lecture/1021

 


by 쥬발자 [2022.07.21 16:30:46]

결과값이 target1,2 는 같은데 target3이 다른게 2개 이상일때도 있어서

결국 union없애고 full outer join 으로 해결했습니다....ㅎ 코멘트 해주신분들 모두 감사합니다 .


by 마농 [2022.07.21 17:00:14]

해결 쿼리 공유 요.


by 우리집아찌 [2022.07.22 13:46:27]

FULL OUTER JOIN 이나 UNION ALL  / GROUP BY 처리나 똑같을텐데요.

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