2017-02-23 67 views
0

如何獲取特定日期的特定列的值與上一日期的同一列的值的差異?SQL可獲取同一列中的值但同一表內的不同日期的差異

Current Table: 
Date   Qty 
8-Jan-17  100 
9-Jan-17  120 
10-Jan-17  180 

Desired Output: 

Date   Diff Qty 
9-Jan-17  20 
10-Jan-17  60 
+0

至極DBMS是你使用什麼呢?你有身份專欄嗎?你的日期總是連續的嗎?沒有重複或失蹤的一天? – Horaciux

回答

0

這將工作,假設日期不重複,兩者之間也沒有差距。

--Sample data as provided. This script works in SQL Server 2005+ 
    CREATE TABLE #Table1 
     ([Date] datetime, [Qty] int) 
    ; 

    INSERT INTO #Table1 
     ([Date], [Qty]) 
    VALUES 
     ('2017-01-08 00:00:00', 100), 
     ('2017-01-09 00:00:00', 120), 
     ('2017-01-10 00:00:00', 180) 
    ; 

    --This script is plain SQL for any DMBS 

    select y.Date, y.Qty-x.Qty as 'Diff Qty' 
    from #table1 x inner join #Table1 y 
    on x.Date+1=y.Date 

結果

+-------------------------+----------+ 
|   Date   | Diff Qty | 
+-------------------------+----------+ 
| 2017-01-09 00:00:00.000 |  20 | 
| 2017-01-10 00:00:00.000 |  60 | 
+-------------------------+----------+ 
相關問題