I have fetched all the rows with most recent rows for every orderID with this VIEW.But I also need another Column " PreviousStatusID " which will store the previous most recent row's StatusID.. Is it possible to implement ? Please Help.
The View :
ALTER VIEW [dbo].[VW_PatientOrderByMaxTimeAddedProc]
AS
SELECT
t.ID,
t.ExamDate,
t.ArrivalTime,
t.Activity,
t.PatientFirstName,
t.PatientMiddleName,
t.PatientLastName,
t.DOB,
t.[Order],
t.ActualExamTimeIn,
t.ActualExamTimeOut,
t.ActualScannerID,
t.ActualExamDate,
t.ActualCustomer,
t.ActualPatientFirstName,
t.ActualPatientLastName,
t.ActualDOB,
t.InsuranceCoID,
t.InsuranceID,
t.StartedInPreAuth,
t.DateReceived,
t.TimeReceived,
FDGPatientOrder,
StatusID,
TimeAdded ,
Notes,
cntID,
empID,
Isotope,
Weight,
Diabetic,
Indication,
[Procedure],
InjectionTime,
PhysicianFirstName ,
PhysicianText,
IndicationDescription
FROM
dbo.smsFDGPatientOrder t
INNER JOIN
dbo.smsFDGPatientOrderStatus ON t.ID = FDGPatientOrder
INNER JOIN
(
SELECT
smsFDGPatientOrder.ID,
MAX(TimeAdded) AS MAX_TIME
FROM
dbo.smsFDGPatientOrder AS smsFDGPatientOrder
INNER JOIN
dbo.smsFDGPatientOrderStatus ON smsFDGPatientOrder.ID = FDGPatientOrder
GROUP BY
smsFDGPatientOrder.ID
)
a ON a.ID = t.ID and a.MAX_TIME = TimeAdded
What version of SQL? In 2012+, you can use the LAG window function to make this not too bad.
SELECT WindowedView.FDGPatientOrder
FROM (
SELECT FDGPatientOrder,
StatusId,
TimeAdded,
MAX(TimeAdded) OVER (PARTITION BY FDGPatientOrder) AS MostRecentTimeAdded,
LAG(StatusId, 1, NULL) OVER (PARTITION BY FDGPatientOrder ORDER BY TimeAdded DESC) AS PrevStatusId
FROM PatientOrders
) WindowedView
WHERE WindowedView.StatusId = 3
AND WindowedView.PrevStatusId IN (4, 9, 10, 20, 21, 22)
AND WindowedView.TimeAdded = WindowedView.MostRecentTimeAdded
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.