我有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 对不起,忘了说我想从一天中选择第一个和最后一个数据
答案 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行。