2009-07-21 51 views
3

我有下面的表:我如何使用最多的時候選擇整行

SignatureID 
PatientID 
PatientVisitID 
TreatAuthDate 
HIPAADate 
DrugTestDate 

現在我有以下Select語句:

SELECT * 
FROM tblSignature 
WHERE PatientID = 12345 

這個SELECT語句返回8行。我需要完成的是獲得MAX TreatAuthDate - 並且使用MAX TreatAuthDate我需要PatientVisitID。然後我需要HipaaDate和DrugTestDate的相同類型的信息。我怎樣才能做到這一點?

回答

10
SELECT TOP 1 * 
FROM tblSignature 
WHERE PatientID = 12345 
ORDER BY 
     TreatAuthDate DESC 

要獲取的「最後」不同的定義最後三個結果,使用:

SELECT * 
FROM (
     SELECT TOP 1 'LastThreatAuth' AS which, ts.* 
     FROM tblSignature ts 
     WHERE PatientID = 12345 
     ORDER BY 
       TreatAuthDate DESC 
     ) SrcTreatAuth 
UNION ALL 
SELECT * 
FROM (
     SELECT TOP 1 'LastHIPAA' AS which, ts.* 
     FROM tblSignature ts 
     WHERE PatientID = 12345 
     ORDER BY 
       HIPAADate DESC 
     ) SrcHIPAA 
UNION ALL 
SELECT * 
FROM (
     SELECT TOP 1 'LastDrugTest' AS which, ts.* 
     FROM tblSignature ts 
     WHERE PatientID = 12345 
     ORDER BY 
       DrugTestDate DESC 
     ) SrcDrugTest 
+0

這只是我需要的。是否有任何建議,我可以得到每個treatauthdate,hipaadate和drugtestdate的前1名?處理日期的前1位可能不是藥物測試的前1位,但我需要患者ID爲前1位治療日期...然後患者ID爲前1位患者...然後患者ID爲前1位藥物測試日期。我怎麼能把它放在一個存儲過程,我們它填充一個對象? – swolff1978 2009-07-21 17:27:35

+0

完美。我修改了上面的代碼添加SELECT * FROM(...)SrcTreatAuth UNION ALL SELECT * FROM(...)SrcHipaa UNION ALL ... – swolff1978 2009-07-21 18:12:54

1
SELECT patientid, max(Treatauthdate), max (HippaDAte) , max (DrugTestDate) 
FROM tblSignature 
WHERE PatientID = 12345 
group by patientid 

注意你不能在這種情況下,要求signatureid因爲你不會過濾任何記錄出來(我做假設signatureid是你的PK)。爲了獲得每個患者每個日期的最大值,可能他們每個人都在不同的行上,因此不會有相同的signatureid。

要獲得每種類型的訪問日期可能會更困難,因爲每個可能是一個單獨的訪問。 嘗試類似

select a.patientid, Treatvisitdate, Treatauthdate,Hippavisitdate, HippaDate, DrugTestvisitdate, 
DrugTestDate 
(SELECT patientid, patientvisitdate as Treatvisitdate, max(Treatauthdate) as Treatauthdate 
FROM tblSignature 
WHERE PatientID = 12345 
group by patientid,patientvisitdate)a 
join 
(SELECT patientid, patientvisitdate as Hippavisitdate, max(HippaDate) as HippaDate 
FROM tblSignature 
WHERE PatientID = 12345 
group by patientid,patientvisitdate) b on a.patientid = b.patientid 
join 
(SELECT patientid, patientvisitdate as DrugTestvisitdate, max(DrugTestDate) as DrugTestDate 
FROM tblSignature 
WHERE PatientID = 12345 
group by patientid,patientvisitdate) c on a.patientid = c.patientid 

您可能需要如果某些日期可能不會在那裏左連接。