我有一个包含以下列的表:
SignatureID
PatientID
PatientVisitID
TreatAuthDate
HIPAADate
DrugTestDate
现在我有以下Select语句:
SELECT *
FROM tblSignature
WHERE PatientID = 12345
此select语句返回8行。我需要完成的是获得MAX TreatAuthDate - 并且使用MAX TreatAuthDate我需要PatientVisitID。然后我需要HipaaDate和DrugTestDate的相同类型的信息。我怎么能这样做?
答案 0 :(得分:10)
SELECT TOP 1 *
FROM tblSignature
WHERE PatientID = 12345
ORDER BY
TreatAuthDate DESC
要获得“last”的不同定义的最后三个结果,请使用:
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
答案 1 :(得分:1)
SELECT patientid, max(Treatauthdate), max (HippaDAte) , max (DrugTestDate)
FROM tblSignature
WHERE PatientID = 12345
group by patientid
注意在这种情况下你不能要求签名,因为你不会过滤掉任何记录(我假设签名是你的PK)。为了获得每个患者每个日期的最大值,可能它们各自位于表的不同行上,因此不会具有相同的签名。
要获得每种类型的访问日期可能会更加困难,因为每个类型可能是单独的访问。 尝试像
这样的东西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
如果某些日期可能不在那里,你可能需要左联接。