最近的行,包含先前最新行的列

时间:2016-03-25 09:51:08

标签: sql sql-server

我已经使用此VIEW为每个orderID获取了最近行的所有行。但是我还需要另一个列“ PreviousStatusID ”,它将存储上一个最近行的StatusID ..是否可能实施?请帮助。

观点:

    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

1 个答案:

答案 0 :(得分:0)

什么版本的SQL?在2012年以上,您可以使用LAG窗口功能来实现这一目标。

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