2017-02-23 29 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 | 
+-------------------------+----------+ 
相关问题