SQL可以获得同一列的值,但是同一个表中的不同日期

时间:2017-02-23 00:21:18

标签: mysql sql oracle-sqldeveloper

如何将特定日期的特定列的值与上一个日期的同一列的值相区别?

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

1 个答案:

答案 0 :(得分: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 |
+-------------------------+----------+