TSQL-使用SQL Server 2008 R2中的先前记录进行计算

时间:2016-02-20 00:11:21

标签: tsql sql-server-2008-r2

-- Create Sample data
Use AdventureWorks2012;

IF OBJECT_ID('TempTable1', 'U') IS NOT NULL
    DROP TABLE TempTable1

-- Grab data from AdventureWorks2012
SELECT SOD.ProductId as ResourceID,
        SOH.DueDate as DueDate,
        SOD.OrderQty as DayIncrement,
        Row_Number() over (PARTITION BY SOD.ProductID ORDER By SOH.DueDate) as JResourceNumber
    INTO TempTable1
    FROM Sales.SalesOrderHeader SOH
        INNER JOIN Sales.SalesOrderDetail SOD
            ON SOH.SalesOrderID = SOD.SalesOrderID
     ORDER by ResourceID, JResourceNumber

-- Reduce records to 2637   
    IF OBJECT_ID('TempTable', 'U') IS NOT NULL
    DROP TABLE TempTable
    SELECT ResourceID, DueDate, DayIncrement, Row_Number() over (ORDER By ResourceID) as JRowNumber, GETDATE() as SchedDate
        INTO TempTable 
        FROM TempTable1 
        WHERE JResourceNumber <= 10
--END   create sample data

--    
-- Calulate a rolling available date for ResourceId = Prev.SchedDate + Curr.DayIncrement
--

IF OBJECT_ID('FINALTABLE', 'U') IS NOT NULL
    DROP TABLE FinalTable
SELECT Curr.ResourceID, Curr.DueDate, Curr.DayIncrement, Curr.JRowNumber as CurrRowNumber, Prev.JRowNumber as PrevJRowNumber,
    Prev.SchedDate  as ShouldBePrevSchedDate,
    Case
        WHEN Curr.ResourceID = Prev.ResourceID THEN DATEADD(DAY, Curr.DayIncrement, Prev.SchedDate) 
    ELSE    GETDATE()
    END AS SchedDate

-- This is the self join 
    FROM TempTable  Curr
        LEFT JOIN TempTable Prev ON Prev.JRowNumber = Curr.JRowNumber - 1

0 个答案:

没有答案