两个查询之间的T-SQL UNION具有不同的顺序,全部由orded

时间:2016-03-14 08:13:23

标签: sql-server union

标题我有这个问题:

我有这两个问题

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 ASCUNION这些查询?

谢谢

编辑:更具体

我有一个包含[state][timestamp]字段的表格。 [State]值可以是3,8或9。 我需要的是选择:
[state] = 9最后3条记录
所有<{1}}

所有[state] != 9

2 个答案:

答案 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