1

当我想从最里面的查询中获取所有 595 个结果行时,我得到了 331 个结果行。它消除 264 行 (595-331=264) 的原因是这 264 行不符合步骤 #2 中的所有条件。确实通过条件的 331 行在 OK 列中获得一个“>>>”。所以,我想显示 331 行的最新日期,另外我想显示其他 264 行的“cid”和 NULL 值,这些值没有通过步骤 #2 中的标准。

作为一名 C# 程序员,我可以想到很多方法来做到这一点。但是,在 SQL 中执行此操作的最佳方法是什么?

/* STEP #4: ORDER RESULTS*/ /* SEE LINE 43 FOR ALL EVENTS */
SELECT          cid
, edate, OK
, (SELECT CASE WHEN OK = '>>>'
THEN DATEDIFF(day, edate, ChartResp.TxPlanDueDate(t2.cid))
ELSE NULL
END
) AS 'DaysBtwnDueDateAndLDOSPrimClin'
, eser, eatt, erecip, Age, ccm, estaff
FROM            (
/* STEP #3: SELECT MOST RECENT EVENT FROM STEP 2 FOR EACH CLIENT*/
SELECT          *
FROM            (
/* STEP #2: SELECT EVENTS THAT PASS FILTER CRITERIA FOR THOSE CLIENTS*/
SELECT          --cid, edate, eser, eatt, erecip, DATEDIFF    (Year, cbd, GetDate()) AS 'Age', ccm, estaff, 
(SELECT CASE WHEN 
(eatt IN (1,2)
AND edate > DATEADD(month, -6, getdate())
AND eser NOT IN (100,115,142)
AND erecip NOT IN ('2','7')
AND (( (erecip = '3') AND (DATEDIFF(Year, cbd, GetDate())<10) ) OR (erecip     <> '3') )
AND ccm = estaff)
THEN '>>>'
ELSE ''
END
) AS 'OK'
,cid, edate, eser, eatt, erecip, DATEDIFF(Year, cbd, GetDate()) AS 'Age',     ccm, estaff
,rownumber() OVER (PARTITION BY cid ORDER BY edate DESC) rn                 
FROM events INNER JOIN client ON ecaseno = cid
LEFT OUTER JOIN doc ON doc.docdbid = client.cid
WHERE client.cid IN (
/* STEP #1: SELECT CLIENTS THAT ARE IN ORIGINAL OVERDUE TX PLAN REPORT */    SELECT client.cid
FROM client LEFT OUTER JOIN admission ON client.cid = admission.cid
WHERE ((client.ctype = 'AC') AND (admission.alapdt IS NULL))
GROUP BY client.cid
HAVING ((ChartResp.TxPlanDueDate(client.cid) < DATEADD(day, - 1, GETDATE())) 
AND (dbo.FFT(client.cid) IS NULL) 
AND (dbo.IsHousingOnly(client.cid) IS NULL) 
AND (DATEDIFF(day, ChartResp.TxPlanDueDate(client.cid),DATEADD(day, - 1,     GETDATE())) > 0))
/* STEP #1 END */
)
AND eser BETWEEN 11 AND 1000
AND ccm = estaff
AND eatt IN (1,2)
AND edate > DATEADD(month, -6, getdate())
AND eser NOT IN (100,115,142)
AND erecip NOT IN ('2','7')
AND (( (erecip = '3') AND (DATEDIFF(Year, cbd, GetDate())<10) ) OR (erecip     <> '3') )
GROUP BY cid, edate, eser, eatt, erecip, cbd, ccm, estaff
/* STEP #2 END */
) t1
WHERE rn = 1-- COMMENT THIS OUT TO SEE ALL EVENTS
/* STEP #3 END */
) t2
ORDER BY cid, edate DESC
4

1 回答 1

0

您还可以使用 CTE 准备所需的数据集,然后使用查询连接回您的 CTE 以获得所需的输出。

于 2013-12-02T12:43:17.997 回答