[221014][AI] SQL union

티나(Tina)·2022년 10월 14일

멋사AI

목록 보기
14/41

union 은 세로로 데이터를 붙여주고, 중복값들을 없앤 데이터를 반환한다.

union all 은 중복 포함 전체를 보여준다.

SELECT* 
From products
where price <=5

union

select * from products
where price >=200

Symmetric Pairs 문제풀기

-- 내가 푼 것....
select 
    case when f1.x <= f1.y then f1.x else f2.x end as x,
    case when f2.x <= f2.y then f2.y else f1.y end as y
from (select x, y from functions where x != y) f1
join (select x, y  from functions where x != y) f2 on f1.x = f2.y

union

select x, y from functions
where x=y
group by x
having count(x) > 1

order by x


-- 문제 풀이
select f1.x, f1.y from functions f1
join functions f2 on f1.x = f2.y and f1.y = f2.x
where f1.x < f1.y

union

select x, y from functions
where x=y
group by x
having count(x) > 1

order by x
  • 나는 x!=y 인 경우로 조인을 했는데, 그냥 조인 한다음에 x!=y 경우를 제거해도 되는거였다!!
  • 순서 정렬하느라 어려웠는데, 조건으로 순서를 써줘서 완전 쉽게 하는걸 보고 놀랐다. 데이터와 조건을 잘 보고 하는게 중요하구나.
profile
열심히 사는 중

0개의 댓글