본문 바로가기

언어 꿀Tip/SQL

(5)
10_05. Difference between timestamp (날짜,시간 차이 구하기) select * from MyTab T where TIMESTAMPDIFF(MINUTE,T.runTime,NOW()) > 20 TIMESTAMPDIFF(단위, 날짜1, 날짜2); SECOND : 초 MINUTE : 분 HOUR : 시 DAY : 일 WEEK : 주 MONTH : 월 QUARTER : 분기 YEAR : 연 출처: https://extbrain.tistory.com/78 [확장형 뇌 저장소]
10_04. 연속적인 log_id에 대한 시작, 끝 log_id 구해라 (Find the Start and End Number of Continuous Ranges) Since some IDs have been removed from Logs. Write an SQL query to find the start and end number of continuous ranges in table Logs. Order the result table by start_id. The query result format is in the following example: select min(log_id) as start_id ,max(log_id) as end_id from ( select log_id ,row_number()over(order by log_id) as log_no from logs ) a1 group by log_id-log_no ;
10_03. 연속적인 숫자 생성 Recursive CTE 사용 Recursive CTE 개념 Recursive CTE (Common Table Expression)는 CTE 중 자기 자신을 반복적으로 호출하는 CTE이다. with recursive temp as ( select 0 as trans_cnt from transactions union select trans_cnt+1 from temp where trans_cnt < ( select count(*) from transactions group by user_id, transaction_date order by 1 desc limit 1) )
10_02. [mysql] moving average & rolling sum mysql을 이용한 moving average 와 rolling sum을 구해보자 위와 같은 형태의 데이터를 이용하여, amount에 대한 moving average window=7 을 구해보자! select visited_on , amount, average_amount from ( select a.visited_on ,row_number()over(order by a.visited_on) as rn ,sum(b.amount) as amount ,round(avg(b.amount),2) as average_amount from ( select visited_on ,sum(amount) as amount from customer group by visited_on) a left join (select v..
10_01. PERCENT_RANK() 와 CUME_DIST() 함수 각 파티션별 행의 순서별 백분율과 현재 행보다 작거나 같은 건수에 대한 누적백분율을 구해보고자 한다! 1. PERCENT_RANK 함수 - 상대적 밴분위수를 RETURN 함 - 0~1 의 범위로 결과값이 나옴 (SQL Server 는 지원하지 x) SELECT DEPT, NAME, SAL ,PERCENT_RANK()OVER(PARTITION BY DEPT ORDER BY SAL) AS PERCENT_RANK FROM TABLE; 2. CUME_DIST 함수 - 현재 행보다 작거나 같은 건수에 대한 누적 백분율 나타냄 - 0~1 의 범위로 결과값이 나옴 (SQL Server 는 지원하지 x) SELECT DEPT, NAME, SAL ,CUME_DIST()OVER(PARTITION BY DEPT ORDER ..