1

How do I get a difference in value of a particular column for a particular date to the value for the same column for the previous date?

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
Ike Walker
  • 64,401
  • 14
  • 110
  • 109
Kris
  • 11
  • 2
  • Wich DBMS are you using exactly? Do you have an identity column? Are your dates always consecutive? no repetition nor missing day? – Horaciux Feb 23 '17 at 00:24

1 Answers1

0

This will work assuming dates are no repeated and there is no gap in between them either.

    --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

Result

+-------------------------+----------+
|          Date           | Diff Qty |
+-------------------------+----------+
| 2017-01-09 00:00:00.000 |       20 |
| 2017-01-10 00:00:00.000 |       60 |
+-------------------------+----------+
Horaciux
  • 6,322
  • 2
  • 22
  • 41