Please start any new threads on our new site at We've got lots of great SQL Server experts to answer whatever question you can come up with.

Our new SQL Server Forums are live! Come on over! We've restricted the ability to create new threads on these forums.

SQL Server Forums
Profile | Active Topics | Members | Search | Forum FAQ
Save Password
Forgot your Password?

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Getting the last event before a time stamp
 Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

Starting Member

8 Posts

Posted - 07/02/2013 :  10:01:49  Show Profile  Reply with Quote
I'm trying to get a query that finds a specific item in a sequence of events which occurs just before an event another table.

My query looks like this:



from Events1 x
left join Events2 y on x.sharedkey = y.sharedkey and y.EventKey = (select top 1 z.eventkey from Events2 z where z.sharedkey = x.sharedkey and z.startdate < x.startdate order by z.startdate desc)

However, I was surprised to discover that with this syntax, SQL ignores the "where z.stardate < x.startdate" clause and simply returns the last event in table y, even if it occurs after the event in table x.

Does TSQL always do this? Is there a way around it to achieve the result I need?

James K
Flowing Fount of Yak Knowledge

3873 Posts

Posted - 07/02/2013 :  10:07:31  Show Profile  Reply with Quote
Just by looking at your code, I can't see a reason why it would ignore the date condition in the where clause. You might be able to simplify the query like shown below:
SELECT x.startdate,
	Events1 x
	(	SELECT TOP (1) z.startdate FROM Events2 z
		WHERE z.sharedkey = x.sharedkey
		AND z.startdate < x.startdate
		ORDER BY z.startdate DESC
	) y

Edited by - James K on 07/02/2013 10:07:48
Go to Top of Page

Flowing Fount of Yak Knowledge

4614 Posts

Posted - 07/02/2013 :  12:01:37  Show Profile  Reply with Quote
Can you post sample data that shows SQL ignoring the predicate?
Go to Top of Page
  Previous Topic Topic Next Topic  
 Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.02 seconds. Powered By: Snitz Forums 2000