Question

I have a table as shown below:

enter image description here

Note: the MAX last_orderdate is 20131015 and the format is yyyymmdd.

I would like to show the final result looks like below:

enter image description here

Is there any query to help me in this as I have 200000 plus records.

Thank you very much for spending your time to look at my question.

Was it helpful?

Solution

For DATEDIFF() function

Try this:

UPDATE A 
SET A.monthDiff = DATEDIFF(mm, CONVERT(DATE, A.orderDate, 112), B.lastOrderDate), 
    A.dayDiff = DATEDIFF(dd, CONVERT(DATE, A.orderDate, 112), B.lastOrderDate)
FROM tableA A, (SELECT MAX(CONVERT(DATE, orderDate, 112)) lastOrderDate FROM tableA) B

Check the SQL FIDDLE DEMO

OUTPUT

| ID | ORDERDATE | MONTHDIFF | DAYDIFF |
|----|-----------|-----------|---------|
|  1 |  20130105 |         9 |     283 |
|  2 |  20130205 |         8 |     252 |
|  3 |  20130305 |         7 |     224 |
|  4 |  20130909 |         1 |      36 |
|  5 |  20131001 |         0 |      14 |
|  6 |  20131015 |         0 |       0 |

OTHER TIPS

try something like this:

declare @a date
set @a='20130105'

declare @b date
set @b='20131015'

select datediff(d,@a,@b) as date_diff,datediff(m,@a,@b) as month_diff

Try this.
select DATEDIFF(DAYOFYEAR,'20131015','20131125').
DAYOFYEAR represents count of days. Depeneds on your requirement, you can change to see month,day or year difference using DATEDIFF

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top