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