I have the following three simple T-SQL queries. First one is to get records within a range of boundaries (DATETIME type):
SELECT value, timestamp
FROM myTable
WHERE timestamp BETWEEN @startDT AND @endDT
the second one is to get the closest record to @startDT (DATETIME type)
SELECT TOP 1
value, timestamp
FROM myTable
WHERE timestamp > @startDT
ORDER BY timestamp DESC
and the last one is to get the closest record after @endDT:
SELECT TOP 1
value, timestamp
FROM myTable
WHERE timestamp < @endDT
ORDER BY timestamp ASC
I would like to get all the records of above three queries as one group of records. I tried to use UNION, but it seems that sub-queries within UNION does not allow ORDER BY clause. Is there efficient way to get my result?
. . * | * * * * * | * . . .
start end
The above graph simply shows the records of *s as my required records, and |...| is the boundaries.
By the way, the amount of data in myTable is huge. My understanding UNION is not an efficient way to get data from UNIONs. Any efficient way to get data without UNION?