Files
TK-FB-Project/api.hyungi.net/db_archive/migrations/009_fix_duplicate_monthly_status.sql
Hyungi Ahn b67362a733 feat: Introduce knex for database migrations
- Adds knex.js to manage database schema changes systematically.
- Creates an initial migration file based on `hyungi_schema_v2.sql` to represent the current database state.
- Adds npm scripts (`db:migrate`, `db:rollback`, etc.) for easy execution of migration tasks.
- Archives legacy SQL files and old migration scripts into the `db_archive/` directory to prevent confusion and clean up the project structure.
2025-12-19 09:43:09 +09:00

73 lines
2.0 KiB
SQL

-- 009_fix_duplicate_monthly_status.sql
-- monthly_worker_status 테이블의 중복 데이터 정리
-- 1. 중복 데이터 확인 (디버깅용)
-- SELECT worker_id, date, COUNT(*) as cnt
-- FROM monthly_worker_status
-- GROUP BY worker_id, date
-- HAVING cnt > 1;
-- 2. 중복 데이터 정리: 같은 worker_id, date에 대해 최신 데이터만 남기고 나머지 삭제
DELETE mws1 FROM monthly_worker_status mws1
INNER JOIN (
SELECT
worker_id,
date,
MAX(id) as keep_id
FROM monthly_worker_status
GROUP BY worker_id, date
) mws2 ON mws1.worker_id = mws2.worker_id
AND mws1.date = mws2.date
AND mws1.id < mws2.keep_id;
-- 3. 중복 제거 후 데이터 재집계 (선택사항)
-- 만약 합산이 필요하다면 다음 프로시저를 실행
DELIMITER $$
CREATE OR REPLACE PROCEDURE ConsolidateDuplicateMonthlyStatus()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE v_worker_id INT;
DECLARE v_date DATE;
-- 중복이 있는 worker_id, date 조합 찾기
DECLARE cur CURSOR FOR
SELECT worker_id, date
FROM monthly_worker_status
GROUP BY worker_id, date
HAVING COUNT(*) > 1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO v_worker_id, v_date;
IF done THEN
LEAVE read_loop;
END IF;
-- 해당 작업자의 해당 날짜 데이터를 재계산하여 업데이트
CALL UpdateMonthlyWorkerStatus(v_date, v_worker_id);
END LOOP;
CLOSE cur;
END$$
DELIMITER ;
-- 4. 프로시저 실행하여 중복 데이터 통합
-- CALL ConsolidateDuplicateMonthlyStatus();
-- 5. 확인: 중복이 남아있는지 체크
SELECT
'중복 체크 완료' as message,
COUNT(*) as remaining_duplicates
FROM (
SELECT worker_id, date, COUNT(*) as cnt
FROM monthly_worker_status
GROUP BY worker_id, date
HAVING cnt > 1
) duplicates;