Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
tandreasen
Starting Member
5 Posts |
Posted - 2010-11-02 : 10:55:45
|
Hey all,I was wondering if there is a way to select a distinct record by date even if dates are identical. I know that Max(date) won't work if two records have the exact same date: with my query, it will always choose both records: i.e.ID ForeignId CreatedDate1 14E78D9B-A75B-4E89-B85E-7D9F82389D9B 2010-10-18 21:20:10.4232 14E78D9B-A75B-4E89-B85E-7D9F82389D9B 2010-10-18 21:20:10.423I have a query which is selecting ForeignId, MAX(CreatedDate), etc.so it should only take the latest record, but there is a remote possibility that this can occur. Is there anything I can do to ensure that it still takes just one of the above records (even if its random, I don't care, I can't have it returning 2 records).Thanks all, T. Andreasen |
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2010-11-02 : 11:41:48
|
Here's one way:select t.id ,t.foreignid ,t.createdDatefrom MyTable tcross apply ( select top 1 id from myTable where foreignid = t.foreignid order by createdDate desc ,id desc ) cawhere t.id = ca.id Be One with the OptimizerTG |
 |
|
tandreasen
Starting Member
5 Posts |
Posted - 2010-11-02 : 13:00:48
|
That works perfectly, thank you! |
 |
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2010-11-02 : 13:05:56
|
You're welcome!Be One with the OptimizerTG |
 |
|
dineshrajan_it
Posting Yak Master
217 Posts |
Posted - 2010-11-03 : 02:32:04
|
Hi another approach using partitionselect F.*from(select id,foreignid,createddate,[RowId]=ROW_NUMBER() over (partition by foreignid,createddate order by id) from Foreignkeys)Fwhere F.RowId =1Iam a slow walker but i never walk back |
 |
|
|
|
|
|
|