Reputation: 21
As the title I have this problem:
I have these two queries
SELECT state, TIMESTAMP
FROM myTable
WHERE state != 9
ORDER BY TIMESTAMP ASC
SELECT TOP (3) state, TIMESTAMP
FROM myTable
WHERE state = 9
ORDER BY TIMESTAMP DESC
is it possible to ORDER BY
again (ORDER BY TIMESTAMP ASC
) the UNION
of these queries?
Thank you
EDIT: to be more specific
I have a table with [state]
and [timestamp]
fields. [State]
value can be 3, 8 or 9.
What I need is to select:
[state] = 9
last 3 records
[state] != 9
all
all ORDER BY [timestamp] ASC
Upvotes: 1
Views: 95
Reputation: 6719
Please try like this
SELECT *
FROM (
SELECT state, TIMESTAMP
FROM myTable
WHERE state != 9
UNION
SELECT TOP (3) state, TIMESTAMP
FROM myTable
WHERE state = 9
ORDER BY (CASE WHEN state = 9 THEN TIMESTAMP END ) DESC
,(CASE WHEN state != 9 THEN TIMESTAMP END ) ASC
) D
Upvotes: 1
Reputation: 82474
You can do this:
SELECT [state], [TIMESTAMP]
FROM
(
SELECT [state], [TIMESTAMP]
FROM myTable
WHERE [state] != 9
UNION
SELECT TOP(3) [state], [TIMESTAMP]
FROM myTable
WHERE [state] = 9
ORDER BY [TIMESTAMP] DESC
) u
ORDER BY [TIMESTAMP] ASC
The order by of the first query is redundant in the union, but the second query needs it for the top(3)
, otherwise you get 3 arbitrary rows.
Upvotes: 3