在每个查询中使用UNION进行ORDER BY

时间:2015-12-04 02:22:30

标签: sql sql-server sql-order-by union

我有UNION ALL

的查询
SELECT TOP 1 * FROM Test WHERE Username LIKE '%me%'
AND DateTime > '2015-12-03' AND DateTime < '2015-12-04' ORDER BY DateTime ACS
UNION ALL
SELECT TOP 1 * FROM Test WHERE Username LIKE '%me%' 
AND DateTime > '2015-12-03' AND DateTime < '2015-12-04' ORDER BY DateTime DESC

但是这个查询在UNION中给了我错误。

我该如何解决?

EDIT 对不起,忘了说我想从一天中选择第一个和最后一个数据

1 个答案:

答案 0 :(得分:1)

您最后一次查询只能在ORDER BY上使用UNION。为了达到您想要的输出:

  

从一天中选择第一个和最后一个数据

您可以使用ROW_NUMBER

;WITH Cte AS(
    SELECT *,
        rn1 = ROW_NUMBER() OVER(ORDER BY DateTime ASC),
        rn2 = ROW_NUMBER() OVER(ORDER BY DateTime DESC)
    FROM Test 
    WHERE
        Username LIKE '%me%' 
        AND DateTime > '2015-12-03' 
        AND DateTime < '2015-12-04'
)
SELECT * FROM Cte WHERE rn1 = 1 UNION ALL
SELECT * FROM Cte WHERE rn2 = 1

您还可以使用OR代替UNION ALL来简化此操作:

;WITH Cte AS(
    SELECT *,
        rn1 = ROW_NUMBER() OVER(ORDER BY DateTime ASC),
        rn2 = ROW_NUMBER() OVER(ORDER BY DateTime DESC)
    FROM Test 
    WHERE
        Username LIKE '%me%' 
        AND DateTime > '2015-12-03' 
        AND DateTime < '2015-12-04'
)
SELECT * FROM Cte WHERE rn1 = 1 OR rn2 = 1

但如果第一个和最后一个数据相同,结果会有所不同。第一个查询将返回2个相同的行,而第二个查询只返回1行。