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

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()

# 최근 1년간 약품별 사용 환자 수 + 3명 이하면 이름 표시
query = """
WITH PatientUsage AS (
    SELECT DISTINCT
        P.DrugCode,
        M.Paname
    FROM PS_sub_pharm P
    JOIN PS_main M ON P.PreSerial = M.PreSerial
    WHERE M.Indate >= CONVERT(VARCHAR, DATEADD(YEAR, -1, GETDATE()), 112)
)
SELECT 
    PU.DrugCode,
    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
FROM PatientUsage PU
GROUP BY PU.DrugCode
HAVING COUNT(*) <= 3
ORDER BY COUNT(*), PU.DrugCode
"""

cur.execute(query)
rows = cur.fetchall()

print(f"=== 최근 1년 사용 환자 3명 이하 약품 ({len(rows)}개) ===\n")
for row in rows[:20]:  # 상위 20개만
    print(f"[{row.DrugCode}] {row.patient_count}명: {row.patient_names}")
