我有以下 SQL 查询,我发现有多个 Consult、SIM、PLAN、TreatmentStart 和 TreatmentFinish 结果。
仅使用MAX
显示最新结果,但我需要说,计划显示在 TreatmentStart 之前最近的最近日期,并使用 SIM 来显示在计划日期之前最近的最近日期。
开始日期基于最近的 TreatmentStart 日期。
我只是想知道是否有人能指出我正确的方向,因为我编写了冗长的 sql 查询,需要超过 2 分钟才能完成......
以下是查询:
SELECT s.Pat_Name, s.IDA, s.Pat_ID1,
ShortDesc = MAX(CASE WHEN s.SysDefStatus = 'SC' THEN s.Short_Desc END),
Consult = MAX(CASE WHEN s.Activity = '123'
AND s.SysDefStatus = 'C' THEN s.App_DtTm END),
SIM = MAX(CASE WHEN s.Activity = '456'
THEN s.App_DtTm END),
PLANNING = MAX(CASE WHEN s.Activity = '789'
THEN s.App_DtTm END),
TreatmentStart = MAX(CASE WHEN s.SysDefStatus = 'SC' THEN s.App_DtTm END),
TreatmentFinished = MAX(CASE WHEN s.SysDefStatus = 'FC' THEN s.App_DtTm END)
FROM vw_Schedule s
WHERE s.Activity IN ('123', '456', '789')
OR s.SysDefStatus IN ('SC', 'FC', 'C')
GROUP BY s.Pat_Name, s.IDA, s.Pat_ID1
)
SELECT Pat_Name,
IDA,
Tx_Intent,
ShortDesc,
Consult,
Days = (DATEDIFF(dd, Consult, SIM)+1)-(DATEDIFF(wk, Consult, SIM)*2),
SIM,
Days = (DATEDIFF(dd, SIM, PLANNING)+1)-(DATEDIFF(wk, SIM, PLANNING)*2),
PLANNING,
Days = (DATEDIFF(dd, PLANNING, TreatmentStart)+1)-(DATEDIFF(wk, PLANNING, TreatmentStart)*2),
TreatmentStart,
Days = (DATEDIFF(dd, TreatmentStart, TreatmentFinished)+1)-(DATEDIFF(wk, TreatmentStart, TreatmentFinished)*2),
TreatmentFinished
FROM T;