SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

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

Ambulare
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:

Select

x.startdate,
y.startdate

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

3557 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,
	y.startdate
FROM
	Events1 x
	OUTER APPLY
	(	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

Lamprey
Flowing Fount of Yak Knowledge

4608 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  
 New 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.06 seconds. Powered By: Snitz Forums 2000