SQL Server Admin
T-SQL Articles

January 02, 2009

Comparing Dates In Two Columns using SQL Server




If you have to choose the most recent date kept in two columns, then here's the query to do so:

-- Create Sample Table
DECLARE @TT table
( ID int,
SomeDate1 datetime,
SomeDate2 datetime
)

-- Create Sample Data
INSERT INTO @TT VALUES ( 1, '1/1/2009', '2/1/2009')
INSERT INTO @TT VALUES ( 2, '2/1/2009', '1/1/2009')
INSERT INTO @TT VALUES ( 3, '3/1/2009', '2/1/2009')
INSERT INTO @TT VALUES ( 4, '3/1/2009', '4/1/2009')
INSERT INTO @TT VALUES ( 5, '4/1/2009', '4/1/2009')
INSERT INTO @TT VALUES ( 6, '1/1/2009', '5/1/2009')
INSERT INTO @TT VALUES ( 7, '8/1/2009', '6/1/2009');
INSERT INTO @TT VALUES ( 8, '9/1/2009', '7/1/2009');
INSERT INTO @TT VALUES ( 9, '3/1/2009', '8/1/2009');
INSERT INTO @TT VALUES ( 10, '4/1/2009', '9/1/2009');


QUERY
SELECT ID,
CASE
WHEN SomeDate1 < SomeDate2
THEN SomeDate2
ELSE SomeDate1
END AS LastDate
FROM @TT

Results
ID LastDate
1 2009-02-01 00:00:00.000
2 2009-02-01 00:00:00.000
3 2009-03-01 00:00:00.000
4 2009-04-01 00:00:00.000
5 2009-04-01 00:00:00.000
6 2009-05-01 00:00:00.000
7 2009-08-01 00:00:00.000
8 2009-09-01 00:00:00.000
9 2009-08-01 00:00:00.000
10 2009-09-01 00:00:00.000


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter



 
  Feedback:

comments

0 Responses to "Comparing Dates In Two Columns using SQL Server"
 

Copyright © 2009-2011 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions