(MS)SQL Query within a Query
July 23, 2009 1:09 AM
Subscribe
I have a basic sql query which returns all jobs run between specified dates as follows:
SELECT job_id, starttime, size
FROM job_history
WHERE (starttime > FromDate) AND (startTime < ToDate)
But I also want the query to return the previous size for that job_id
I've tried:
SELECT job_id, starttime, size,
(SELECT Top 1 size FROM job_history
WHERE starttime [less than] FromDate
AND job_id = job_id
ORDER BY starttime DESC) AS Previous_Size
FROM job_history
WHERE (starttime > FromDate) AND (startTime [less than] ToDate)
I'm guessing that I need a variable in ther or something but I'm a bit out of my depth.
([less than] used to indicate opposite of > as it seems to dissapear when posted.)
posted by xla76 to computers & internet (4 comments total)
1 user marked this as a favorite
SELECT a.job_id, a.starttime, a.size,
(SELECT Top 1 b.size FROM job_history AS b
WHERE b.starttime [less than] b.FromDate
AND a.job_id = b.job_id
ORDER BY b.starttime DESC) AS Previous_Size
FROM job_history AS a
WHERE (a.starttime > a.FromDate) AND (a.startTime [less than] a.ToDate)
posted by radicarian at 1:33 AM on July 23