
/ / / 비가 추적추적 / / /
오히려 좋아.
# union/union all 기본구조
select name,
goods_nm,
pay_date --- #컬럼 순서가 같고, 그 형식이 같아야 함
from 테이블명1
union (all) #수직결합 명시
select
name,
goods_nm,
pay_date
from 테이블명 2
JOIN: 여러 개의 SELECT 문의 결과를 단일 결과 세트로 연결, 두 개의 테이블을 결합하는 역할.
두 개의 데이터 셋을 조인하는 방법.
✔️ 문제 #1: CASE WHEN 구문과 JOIN 함수 사용하여 데이터 값 추출
✔️ 작성 쿼리
select a.gb,
count(*) as usercnt
from
(
select case when p.game_account_id is null then '결제안함'
else '결제함' end as gb
from users u left join payment p
on u.game_account_id = p.game_account_id
group by u.game_account_id
) a
group by a.gb
order by 2 desc
;
✔️ 실행 결과
✔️ 문제 #2: 조건부 테이블 JOIN 후 기준에 따른 데이터 추출
✔️ 작성 쿼리
select *
from
(
select u.game_account_id,
count(distinct u.game_actor_id) as actorcnt,
sum(distinct p.pay_amount) as sumamount
from users u inner join payment p
on u.game_account_id = p.game_account_id
where u.serverno > 1 and p.pay_type = 'CARD'
group by u.game_account_id
) a
where a.actorcnt >= 2
;
# 매출에 해당하는 pay_amount의 중복값을 제거하는 함수를
사용하는 것을 피하기 위해 작성한 다른 쿼리
select *
from
(
select u.game_account_id,
count(u.game_actor_id) actorcnt,
a.sumamount
from users u inner join
(
select game_account_id,
sum(pay_amount) sumamount
from payment
where pay_type='CARD'
group by game_account_id
) a
on u.game_account_id = a.game_account_id
where u.serverno >= 2
group by u.game_account_id
) b
where b.actorcnt >= 2
order by b.game_account_id
;
✔️ 실행 결과
✔️ 문제 #3: 조건부 테이블 JOIN 후 기준에 따른 데이터 추출
✔️ 작성 쿼리
select c.serverno,
round(avg(c.diffdate)) avgdiffdate
from
(
select a.serverno,
datediff(b.recentpay, a.`date`) diffdate
from
(
select game_account_id,
`date`,
serverno
from users u
) a join
(
select game_account_id,
date_format(max(approved_at),'%Y-%m-%d') recentpay
from payment p
group by game_account_id
) b
on a.game_account_id = b.game_account_id
) c
where diffdate >= 10
group by c.serverno
order by c.serverno desc
;
✔️ 실행 결과
오늘의 한 줄.
코드카타 하고, 강의도 다 듣고, SQL 세션 과제까지 끝까지 풀어낸 나, 칭찬해.