标题我有这个问题:
我有这两个问题
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
是否可以ORDER BY
再次(ORDER BY TIMESTAMP ASC
)UNION
这些查询?
谢谢
编辑:更具体
我有一个包含[state]
和[timestamp]
字段的表格。 [State]
值可以是3,8或9。
我需要的是选择:
[state] = 9
最后3条记录
所有<{1}}
所有[state] != 9
答案 0 :(得分:3)
你可以这样做:
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
第一个查询的顺序在union中是多余的,但是第二个查询需要top(3)
,否则你会获得3个任意行。
答案 1 :(得分:0)
请尝试这样
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