-- ============================================
-- 调试队列日期问题
-- 用途：检查数据库中的 queue_date 字段值，找出为什么查询不到数据
-- ============================================

-- 1. 查看所有队列记录的日期分布
SELECT 
    queue_date,
    status,
    COUNT(*) AS count,
    STRING_AGG(patient_name, ', ') AS patients
FROM hisdev.triage_queue_item
WHERE tenant_id = 1
  AND delete_flag = '0'
GROUP BY queue_date, status
ORDER BY queue_date DESC, status;

-- 2. 查看指定科室的所有记录（不限制日期）
SELECT 
    id,
    queue_date,
    status,
    patient_name,
    organization_id,
    organization_name,
    queue_order,
    create_time
FROM hisdev.triage_queue_item
WHERE tenant_id = 1
  AND delete_flag = '0'
  AND organization_id = 1995302136614969300
ORDER BY queue_date DESC, queue_order ASC;

-- 3. 查看今天的记录（使用 CURRENT_DATE）
SELECT 
    id,
    queue_date,
    status,
    patient_name,
    organization_id,
    queue_order
FROM hisdev.triage_queue_item
WHERE tenant_id = 1
  AND delete_flag = '0'
  AND queue_date = CURRENT_DATE
  AND organization_id = 1995302136614969300
ORDER BY queue_order ASC;

-- 4. 查看 2026-01-16 的记录
SELECT 
    id,
    queue_date,
    status,
    patient_name,
    organization_id,
    queue_order
FROM hisdev.triage_queue_item
WHERE tenant_id = 1
  AND delete_flag = '0'
  AND queue_date = '2026-01-16'::DATE
  AND organization_id = 1995302136614969300
ORDER BY queue_order ASC;

-- 5. 查看 2025-01-16 的记录（可能是昨天的数据）
SELECT 
    id,
    queue_date,
    status,
    patient_name,
    organization_id,
    queue_order
FROM hisdev.triage_queue_item
WHERE tenant_id = 1
  AND delete_flag = '0'
  AND queue_date = '2025-01-16'::DATE
  AND organization_id = 1995302136614969300
ORDER BY queue_order ASC;

-- 6. 查看最近的记录（最近7天）
SELECT 
    queue_date,
    status,
    COUNT(*) AS count
FROM hisdev.triage_queue_item
WHERE tenant_id = 1
  AND delete_flag = '0'
  AND queue_date >= CURRENT_DATE - INTERVAL '7 days'
GROUP BY queue_date, status
ORDER BY queue_date DESC, status;

-- 7. 检查系统当前日期（PostgreSQL）
SELECT CURRENT_DATE AS current_date_in_db;

-- 8. 查看所有状态为 WAITING 或 SKIPPED 的记录（不限制日期）
SELECT 
    id,
    queue_date,
    status,
    patient_name,
    organization_id,
    queue_order
FROM hisdev.triage_queue_item
WHERE tenant_id = 1
  AND delete_flag = '0'
  AND status IN ('WAITING', 'SKIPPED')
  AND organization_id = 1995302136614969300
ORDER BY queue_date DESC, queue_order ASC;

