데이터 분석

[day27] 어느덧 4주차 마무리

경 민 2025. 3. 14. 21:40
더보기

👩🏻‍💻  TODAY I LEARN

📌 SQL

- QCC

- 코드카타 복습

- 시간제한 두고 풀기

📌 Python 

- 라이브세션 3회차 복습 (pivot, 기타 매서드) ➜ SQL 공부 끝나니까 6시.. 급한 개인과제부터 하느라 못 함

- 개인과제 5번 기본 개념까지 학습

- 전처리&시각화 3주차까지 주말에 열공할 일만 남았네..

📌 아티클 미션 (오후 7시)

1. SQL 

1-1. QCC

1️⃣ 1번 문항

 

'0이거나 null인 경우 제외 = 0, null 둘 다 제외'

 

where (GNPOld <> 0 or GNPOld is not null) —> 0,null 가능

where (GNPOld <> 0 And GNPOld is not null) —> 0,null 불가능

 

처음에 or로 묶었다가 검토하면서 수정했다. ^ㅠ^

 

2️⃣ 3번 문항

제출한 쿼리

select 
  ci.name as CITY_NAME,
  co.name as COUNTRY_NAME,
  co.continent as CONTINTENT,
  co.population as POPULATION
from country co
left join city ci
on co.code = ci.countrycode
where 
  ci.name is not null
  and co.population in (
                      select max(population)
                      from country co2
                      group by continent)
group by co.continent

 

 

Q. continent별로 대응시키는 조건 필요하지 않을까?
where co2.continent = co.continent

 

응 맞아..

제출하고 발견했네 . . . .

 

 

+

그리고

도시의 인구 수를 구해야 한다.

나는 국가의 인구 수를 구했다.

문제를 똑바로 파악합시당

(내가 작성한) 방법1.  서브쿼리로 max구해서 일치하면 출력

select 
    ci.name city_name,
    co.name country_name,
    co.continent continent,
    ci.population
from city ci
join country co
on ci.countrycode = co.code
where ci.population in (
                    select max(ci2.population)
                    from city ci2
                    join country co2
                    on ci2.countrycode = co2.code
                      and co2.continent = co.continent  -- 최댓값 구해서 어디에 매칭시킬건지 알려줄게
                    group by co2.continent)
order by population desc

 

방법2. rank 함수로 최대 인구수 구하고 그 행 전부 출력

select city_name, country_name, continent, population
from(
select 
    ci.name as city_name,
    co.name as country_name,
    co.continent,
    ci.population,
    rank() over(partition by co.continent order by ci.population desc) as rnk
from city ci
inner join country co
on ci.countrycode = co.code) a
where rnk =1
order by population desc

 

 

방법1,2 둘 다 max(ci.population) 값이 중복 될 경우 전부 출력된다.

만약 하나의 도시만 출력하라고 했으면 row_number로 구해줘야 함!

 

⭐️ 학습 포인트
순위 구해서 그 순위에 해당하는 행을 보고 싶으면 window함수를 쓰자
훨씬 직관적이고 간단해진다.

1-2. 코드카타 복습

1) 97번

방법. having 으로 조건 넣어주기

select 
    round(
    (
    select
        count(1)
    from delivery d1
    group by customer_id
    having min(order_date) = customer_pref_delivery_date
    ) / count(distinct customer_id)*100,2) as immediate_percentage
from delivery

저번에는 방법2로 풀었는데, 오늘은 새로운 방법으로 풀어봄

 

방법2. 조건 True면 1, False면 0 을 출력하는 새로운 컬럼 생성 ➜ 전체 행 변화 X

select
    round(sum(a.immediate) / count(1)*100,2) as immediate_percentage
from (
select
    case when min(order_date) = customer_pref_delivery_date then 1
        else 0 end as immediate
from delivery
group by customer_id ) a

 

 

1-3. 오늘의 코드카타

1) 109번

방법1. 셀프조인 (근데 이제 +1을 곁들인 ..)

select l1.num as ConsecutiveNums
from logs l1
join logs l2 on l1.id = l2.id+1     -- lag(num,1) over()랑 같은 의미네?
join logs l3 on l1.id = l3.id+2
where l1.num = l2.num and l1.num = l3.num

근데 이건 id가 규칙적으로 증가하는 게 아니면 쓸 수 없는 쿼리이다.

id 기준으로 찾아보지 않고 num 자체만으로 비교하려면?

방법2,3 참고!

 

방법2. lag 함수

select
    num as ConsecutiveNums
from
(select
    *,
    lag(num,1) over() num2,
    lag(num,2) over() num3
from logs) a
where num=num2 and num2=num3

 

방법1로 풀다가 결과물이 lag 썼을 때랑 비슷하길래 이렇게도 풀어봤다.

맞게 푼 건지 돌려봤는데

이게 더 깔끔하다고 챗한테 칭찬받음

 

⠀⠀  ⡠⠒⢄  ⠀⠀   ⡴⠒⢦⣀⠔⠒⢄

⠀⠀   ⠉⠉⠉⣽⠀⢴⣷⠛⢲⠶⠚⣄

⠀⠀ ⠀⠀⠀  ⠀⠀⠓⠚⠛⠤⡞⠛⠀⡞

 ⠀⠀⢸ ⠀⠀⠀⠀⠀⠀⠀ ⠀⠀⠀⠉⢉⣇⣀⣀

  ⠉⠉⣇⡀   ⣶⠀⠀  ⣀⠀⠀  ⣶⠀⠀⣾⠤⠤

  ⠡⠨ ⣃⡀ ⠀⠀⠀⠉⠀⠀⠀      ⡸⠒⠒

   ⢸⢴⠉⠂⣘⠖⢶⠒⠒⡶⢲⠒⡞⢣

⠢⣉⣁⠜⠒⢄  ⠉⠉⠀⡠⠋⠉⠉

⠀⠀    ⠑⠒⠓⠒

 

근데 사실 이 문제 보고 젤 처음 생각 난 건 lead 였단 말이지..

lead로도 풀어보자.

 

방법3. lead 함수

select
    num as ConsecutiveNums
from
(select
    *,
    lead(num,1) over() num2,
    lead(num,2) over() num3
from logs) a
where num=num2 and num2=num3

 

lag ↔ lead만 해줌

where 절에 해당하는 행이 앞에 오느냐 뒤에 오느냐의 차이!

lead는 뒤에 거 끌어오는 거니까 앞에 오겠고,

lag는 앞에 거 끌어오는 거니까 뒤에 가겠지

 

 

2. Python

2-1. 개인과제 5번

✅ 핵심 개념

 in, not in, startswith, endswith, split

 


3. 아티클 미션

 

[아티클 미션] -15 데이터의 신뢰성

양질의 데이터를 판별하는 5가지 방법 : 2 믿을 수 있는 데이터인가? | 요즘IT데이터 신뢰성이란 데이터가 얼마나 실제 정보를 똑바로 담고 있는가에 대한 개념으로 이해하면 좋습니다. 데이터 자

rosenps3.tistory.com