카테고리 없음

[TIL] 74일차

unoori 2025. 1. 24. 09:14

qcc 7회차

 

3번문제

# 3 정답1
WITH running_time as(
	SELECT *
		  ,lead(status_time) OVER (PARTITION BY server_id ORDER BY status_time) AS next_status_time
		  ,lead(session_status) OVER (PARTITION BY server_id ORDER BY status_time) AS next_session_status
	FROM server_utilization 
)
SELECT FLOOR(SUM(TIMESTAMPDIFF(SECOND, status_time, next_status_time) / 86400)) uptime_days
FROM running_time
where session_status = 'start'
and next_session_status = 'stop';

 

이 SQL 쿼리는 서버의 가동 시간(uptime)을 계산하여 **가동 시간(일 단위)**으로 반환합니다. 아래에서 쿼리를 단계별로 분석합니다.

 

1. WITH running_time CTE

 

WITH running_time as(

SELECT *,

      lead(status_time) OVER (PARTITION BY server_id ORDER BY status_time) AS next_status_time,

      lead(session_status) OVER (PARTITION BY server_id ORDER BY status_time) AS next_session_status

FROM server_utilization 

)

 

기능:

server_utilization 테이블의 데이터를 준비.

LEAD 함수로 다음 값을 가져옴:

next_status_time: 현재 행의 status_time 다음에 오는 시간.

next_session_status: 현재 행의 session_status 다음에 오는 상태.

PARTITION BY server_id:

server_id별로 데이터를 나누어 독립적으로 계산.

ORDER BY status_time:

status_time 기준으로 정렬하여 다음 값(LEAD)을 논리적으로 계산.

 

2. 최종 SELECT

 

SELECT FLOOR(SUM(TIMESTAMPDIFF(SECOND, status_time, next_status_time) / 86400)) uptime_days

FROM running_time

WHERE session_status = 'start'

  AND next_session_status = 'stop';

 

주요 작업:

조건:

session_status = 'start': 현재 행이 서버가 시작한 상태.

next_session_status = 'stop': 다음 행이 서버가 중단된 상태.

가동 시간 계산:

TIMESTAMPDIFF(SECOND, status_time, next_status_time):

status_timenext_status_time의 차이를 초 단위로 계산.

SUM(...) / 86400:

모든 초 단위의 가동 시간을 합산하고, 이를 하루(초 단위: 86400)로 나누어 일 단위로 변환.

FLOOR(...):

계산된 결과를 내림하여 정수로 만듦.

 

최종 출력

:

uptime_days: startstop 사이의 서버 가동 시간 합계(일 단위).

 

활용 예시

서버의 전체 가동 시간을 계산하여 시스템 가용성 분석에 활용.

예를 들어, 데이터 센터나 클라우드 서버의 가동률(SLA)을 분석하거나, 특정 서버의 안정성을 평가할 수 있습니다.