-- 修复手术安排中申请科室名称为空的数据
-- 执行时间：2026-03-31
-- 说明：填充 cli_surgery 表中 apply_dept_name 为空的记录

-- 1. 查看当前申请科室名称的填充情况
SELECT
    COUNT(*) as total_count,
    COUNT(apply_dept_id) as has_apply_dept_id_count,
    COUNT(apply_dept_name) as has_apply_dept_name_count,
    COUNT(*) - COUNT(apply_dept_name) as null_count
FROM public.cli_surgery
WHERE delete_flag = '0';

-- 2. 修复申请科室名称（关联 adm_organization 表）
UPDATE public.cli_surgery s
SET apply_dept_name = o.name
FROM public.adm_organization o
WHERE s.apply_dept_id = o.id
AND s.apply_dept_name IS NULL
AND s.delete_flag = '0';

-- 3. 对于 apply_dept_id 为空的记录，尝试从其他来源获取
-- 例如从就诊记录中查找科室信息
UPDATE public.cli_surgery s
SET apply_dept_name = d.dept_name
FROM public.adm_encounter e
JOIN public.adm_department d ON e.dept_id = d.id
WHERE s.encounter_id = e.id
AND s.apply_dept_name IS NULL
AND s.apply_dept_id IS NULL
AND s.delete_flag = '0';

-- 4. 再次查询，验证修复结果
SELECT
    id,
    surgery_no,
    patient_name,
    apply_dept_id,
    apply_dept_name,
    create_time
FROM public.cli_surgery
WHERE delete_flag = '0'
AND (apply_dept_name IS NULL OR apply_dept_name = '')
ORDER BY create_time DESC
LIMIT 20;
