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
 General SQL Server Forums
 New to SQL Server Programming
 How to return only the highest value per field
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

crugerenator
Posting Yak Master

126 Posts

Posted - 11/06/2012 :  17:27:07  Show Profile  Send crugerenator an AOL message  Reply with Quote
This is part of a subselect in a where clause and is driving me crazy.

It's in a subselect because the query needs to figure out the top (1) run id of a job that runs multiple times her day. What I'm trying to do is expand the query to provide results for the top (1) runid for ALL jobs.

Here is the subselect:

SELECT TOP (1) id 
FROM dbo.ENV_TABLE_NAME 
WHERE (service_id = '63') 
and (run_date between '11/05/2012 21:00:00' and '11/6/2012 21:00:00') 


The query sets runid of another table = to the top (1) id returned from this query. What I want to do is have the subselect return the top (1) id for all server results, and instead of setting the runid = to the top (1) id, it will use in since the subselect will be returning multiple id's.

For example:


runid in (SELECT id 
FROM dbo.ENV_TABLE_NAME
WHERE (rundate between '11/05/2012 21:00:00' and '11/6/2012 21:00:00') 
ORDER BY id DESC)) 


This works fine, but I need to return only the top id per all service_id's between the time frame specified. Is this possible?

bandi
Flowing Fount of Yak Knowledge

India
2169 Posts

Posted - 11/06/2012 :  23:55:38  Show Profile  Reply with Quote

SELECT service_id, id 
FROM dbo.ENV_TABLE_NAME t1
WHERE (run_date between '11/05/2012 21:00:00' and '11/6/2012 21:00:00')
AND ID = (SELECT top 1 ID 
			FROM dbo.ENV_TABLE_NAME t2
			WHERE (run_date between '11/05/2012 21:00:00' and '11/6/2012 21:00:00')
			AND t1.service_id = t2.service_id
			ORDER BY ID DESC)


--
Chandu
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.08 seconds. Powered By: Snitz Forums 2000