我正在尝试使用sql获取给定日期范围内每个月的第一条记录和最后一条记录。我有一个示例代码,我刚刚选择了日期范围内的所有内容,现在我必须提取每个月的第一个和最后一个记录。
SELECT PurOrderNum,
OrderDate
FROM Purchasing.PurOrder
WHERE OrderDate >= '2013-02-28'
AND OrderDate <= '2014-12-29'
答案 0 :(得分:2)
您可以尝试row_number():
WITH FilterOrders AS (
SELECT
*
, MinDatePrio = ROW_NUMBER() OVER (PARTITION BY YEAR(OrderDate), MONTH(OrderDate) ORDER BY OrderDate, PurOrderNum)
, MaxDatePrio = ROW_NUMBER() OVER (PARTITION BY YEAR(OrderDate), MONTH(OrderDate) ORDER BY OrderDate DESC, PurOrderNum DESC)
FROM Purchasing.PurOrder
WHERE OrderDate BETWEEN '2013-02-28' AND '2014-12-29'
) SELECT PurOrderNum, OrderDate FROM FilterOrders
WHERE MinDatePrio = 1 OR MaxDatePrio = 1
<强>结果:强>