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.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to return only the highest value per field

Author  Topic 

crugerenator
Posting Yak Master

126 Posts

Posted - 2012-11-06 : 17:27:07
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
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2012-11-06 : 23:55:38
[code]
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)[/code]

--
Chandu
Go to Top of Page
   

- Advertisement -