Search code examples
sqlsql-serverdb2datediff

SQL Server Datediff() function not working


For SQL Server I have some difficulty getting the difference between times

I'm using the SQuirell client but am unsure if Datediff is a function

Example of my data

Person | Times Ordered | Date order placed | Date order placed (Timestamp) 
---------------------------------------------------------------------
Jane   |      1        |   5/5/2017        |  5/5/2017 01:01:56.95
Jane   |      2        |   6/2/2017        |  6/2/2017 18:41:34.486
Jane   |      3        |   7/5/2018        |  7/5/2018 08:31:45.759
Donald |      1        |   5/2/2017        |  5/2/2017 21:22:44.23 
Donald |      2        |   8/2/2018        |  8/2/2018 22:25:50.323 
Ron    |      1        |   4/8/2017        |  4/8/2017 03:10:25.55
Ron    |      2        |   8/30/2017       |  8/30/2017 19:20:20.55
Ron    |      3        |   5/24/2018       |  5/24/2018 09:35:55.85
Jim    |      1        |   2/15/2017       |  2/15/2017 20:15:55.45 
Jim    |      2        |   9/6/2018        |  9/6/2018 23:20:50.4

I've tried the following SQL Server query

select
a.Person,
a.times_ordered,
a.date_order_placed,
datediff(month, lag(a.Date_order_placed_ts) over(partition by a.persion order by a.date_order_placed)) as Month_Difference
from table_1 a

Errors I'm getting

SQLERRMC: MONTH SQLState: 42703 ErrorCode: -206

SQLERRMC: MONTH SQLState: 56098 ErrorCode: -727

I'm trying to get the difference in time between the most recent order and the order just placed before that.

Desired Output Example

Person | Times Ordered | Date order placed | Date order placed (Timestamp) | Month_difference
----------------------------------------------------------------------------------------------
Jane   |      1        |   5/5/2017        |  5/5/2017 01:01:56.95         | <Null>
Jane   |      2        |   6/2/2017        |  6/2/2017 18:41:34.486        |   1
Jane   |      3        |   7/5/2018        |  7/5/2018 08:31:45.759        |   13
Donald |      1        |   5/2/2017        |  5/2/2017 21:22:44.23         | <Null>
Donald |      2        |   8/2/2018        |  8/2/2018 22:25:50.323        |   15
Ron    |      1        |   4/8/2017        |  4/8/2017 03:10:25.55         | <Null>
Ron    |      2        |   8/30/2017       |  8/30/2017 19:20:20.55        |   4
Ron    |      3        |   5/24/2018       |  5/24/2018 09:35:55.85        |   9
Jim    |      1        |   2/15/2017       |  2/15/2017 20:15:55.45        | <Null>
Jim    |      2        |   9/6/2018        |  9/6/2018 23:20:50.4          |   19

Solution

  • There is no such function in db2.
    Try TIMESTAMPDIFF instead.