我有一个SQL查询:
WITH Cte AS
(
SELECT DateTime,
rn1 = ROW_NUMBER() OVER(ORDER BY DateTime ASC),
rn2 = ROW_NUMBER() OVER(ORDER BY DateTime DESC)
FROM
Test
WHERE
Username = 'ME'
AND DateTime > '2016-01-05'
AND DateTime < '2016-01-06'
)
SELECT * FROM Cte WHERE rn1 = 1 UNION ALL
SELECT * FROM Cte WHERE rn2 = 1
通过此查询,我成功获取 2016年1月5日的第一个和最后一个数据
但是,我怎样才能获得第一个和最后一个数据,例如,从 1月5日到 1月8日?
也就是说,我想从1月5日获得第一个和最后一个数据,然后是1月6日的第一个和最后一个数据,然后是1月7日的第一个和最后一个数据,然后是第一个和第一个数据。最后的数据来自1月8日。
你可以看到,订单有点乱 我希望它看起来像这样答案 0 :(得分:2)
要获取1月5日至8日每天的第一个和最后一个数据,您需要在PARTITION BY
条款中添加OVER
:
WITH Cte AS(
SELECT
DateTime,
rn1 = ROW_NUMBER() OVER(PARTITION BY CAST(DateTime AS DATE) ORDER BY DateTime ASC),
rn2 = ROW_NUMBER() OVER(PARTITION BY CAST(DateTime AS DATE) ORDER BY DateTime DESC)
FROM Test
WHERE
Username = 'ME'
AND DateTime >= '20160105'
AND DateTime < '20160109'
)
SELECT * FROM Cte WHERE rn1 = 1 OR rn2 = 1
编辑:
WITH Cte AS(
SELECT
CAST(DateTime AS DATE),
DateTime,
rn1 = ROW_NUMBER() OVER(PARTITION BY CAST(DateTime AS DATE) ORDER BY DateTime ASC),
rn2 = ROW_NUMBER() OVER(PARTITION BY CAST(DateTime AS DATE) ORDER BY DateTime DESC)
FROM Test
WHERE
Username = 'ME'
AND DateTime >= '20160105'
AND DateTime < '20160109'
)
SELECT * FROM Cte WHERE rn1 = 1 OR rn2 = 1
ORDER BY CAST(DateTime AS DATE)