SQL_코드카타(2024.01.10)

김수경·2024년 1월 10일

코드카타

목록 보기
16/29

84. Customer Who Visited but Did Not Make Any Transactions

테이블 1 : Visits

+-------------+---------+
| Column Name | Type |
+-------------+---------+
| visit_id | int |
| customer_id | int |
+-------------+---------+
visit_id is the column with unique values for this table.
This table contains information about the customers who visited the mall.

테이블 2 : Transactions

+----------------+---------+
| Column Name | Type |
+----------------+---------+
| transaction_id | int |
| visit_id | int |
| amount | int |
+----------------+---------+
transaction_id is column with unique values for this table.
This table contains information about the transactions made during the visit_id.

문제

거래 없이 방문한 사용자의 ID와 이러한 유형의 방문 횟수를 찾는 솔루션을 작성하세요.
임의의 순서 로 정렬된 결과 테이블을 반환합니다 .

Output

+---------------+---+
| 고객_ID | count_no_trans |
+---------------+---+
| 54 | 2 |
| 30 | 1 |
| 96 | 1 |
+---------------+---+

👩🏻‍💻 My Coding

[조건]

  • Visit 테이블에는 있으나 Transaction 테이블에는 없는 고객ID
  • 그 고객 ID의 방문 횟수
select customer_id,
       count(*) as count_no_trans
from visits vis left join transactions tra on vis.visit_id = tra.visit_id
where tra.visit_id is null
group by vis.customer_id 

85. Rising Temperature

테이블 : Weather

+---------------+---------+
| Column Name | Type |
+---------------+---------+
| id | int |
| recordDate | date |
| temperature | int |
+---------------+---------+
id is the column with unique values for this table.
This table contains information about the temperature on a certain day.

문제

Id이전 날짜(어제)에 비해 온도가 더 높은 모든 날짜를 찾는 솔루션을 작성하세요 .
어떤 순서로든 결과 테이블을 반환합니다 .

Output

+----+
| id |
+----+
| 2 |
| 4 |
+----+

👩🏻‍💻 My Coding

[조건]

  • 조건문으로 날짜를 이전 날짜와 비교 >> lag
select id
from
(
select *,
lag(temperature, 1) over(order by recordDate) as pre_tem
from weather
) a
where temperature > pre_tem

또는 테이블을 두개로 지정하는 방법도 있다.

SELECT w1.id
FROM Weather w1, Weather w2
WHERE w1.Temperature > w2.Temperature AND DATEDIFF(w1.recordDate , w2.recordDate) = 1

👀 LAG, LEAD

  • LAG : 이전 행의 값을 불러옴
  • LEAD : 다음 행의 값을 불러옴
-- lag 함수로 불러온 값 확인해보면 pre_tem에 temperatured의 이전행 값이 불러와진다.
select *,
lag(temperature, 1) over(order by recordDate) as pre_tem
from weather
idrecordDatetemperaturepre_tem
12015-01-0110null
22015-01-022510
32015-01-032025
42015-01-043020

profile
잘 하고 있는겨?

0개의 댓글