SQL显示所有行

时间:2013-11-08 16:41:10

标签: sql sql-server tsql

当我想从最内层的查询中获取所有595时,我得到331个结果行。它消除264行(595-331 = 264)的原因是那些264行不符合STEP#2中的所有行。通过条件的331行获得'>>>'在OK列中。所以,我想显示331行的最新日期,另外我想显示其他264中没有通过STEP#2标准的'​​cid'和NULL值。

作为一名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

1 个答案:

答案 0 :(得分:0)

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