# -*- coding: utf-8 -*-
import pyodbc
import time

conn_str = (
    'DRIVER={ODBC Driver 17 for SQL Server};'
    'SERVER=192.168.0.4\\PM2014;'
    'DATABASE=PM_PRES;'
    'UID=sa;'
    'PWD=tmddls214!%(;'
    'TrustServerCertificate=yes;'
    'Connection Timeout=10'
)

conn = pyodbc.connect(conn_str, timeout=10)
cur = conn.cursor()

# 현재 쿼리 성능 측정
start = time.time()

query = """
WITH PatientUsage AS (
    SELECT DISTINCT
        P.DrugCode,
        M.Paname,
        MAX(CASE WHEN M.Indate >= '20260306' AND M.Indate <= '20260306' THEN 1 ELSE 0 END) as used_in_period
    FROM PS_sub_pharm P
    JOIN PS_main M ON P.PreSerial = M.PreSerial
    WHERE M.Indate >= CONVERT(VARCHAR, DATEADD(YEAR, -1, GETDATE()), 112)
    GROUP BY P.DrugCode, M.Paname
)
SELECT 
    PU.DrugCode as drug_code,
    COUNT(*) as patient_count,
    STUFF((
        SELECT ', ' + PU2.Paname
        FROM PatientUsage PU2
        WHERE PU2.DrugCode = PU.DrugCode
        ORDER BY PU2.Paname
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') as patient_names,
    STUFF((
        SELECT ', ' + PU3.Paname
        FROM PatientUsage PU3
        WHERE PU3.DrugCode = PU.DrugCode AND PU3.used_in_period = 1
        ORDER BY PU3.Paname
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)'), 1, 2, '') as today_patients
FROM PatientUsage PU
GROUP BY PU.DrugCode
HAVING COUNT(*) <= 3
"""

cur.execute(query)
rows = cur.fetchall()
elapsed = time.time() - start

print(f"결과: {len(rows)}개 약품")
print(f"실행 시간: {elapsed:.2f}초")
print(f"약품당: {elapsed/len(rows)*1000:.2f}ms" if rows else "")
